Difference Between Abstraction and Encapsulation in C#

Difference Between Abstraction and Encapsulation in C#

Both Abstraction and Encapsulation are fundamental concepts of Object-Oriented Programming (OOP), but they serve different purposes. Let’s break them down clearly with code examples and key comparisons.


๐Ÿ” What is Abstraction?

Abstraction is the process of hiding implementation details and exposing only the essential features of an object. It focuses on what an object does rather than how it does it.

✅ How Abstraction is Implemented:

๐Ÿงช Example:

public interface IPrinter
{
    void Print();
}

public class LaserPrinter : IPrinter
{
    public void Print()
    {
        // Complex logic hidden from user
        Console.WriteLine("Printing document...");
    }
}

Here, the user interacts with the IPrinter interface without knowing the internal logic of LaserPrinter.

๐Ÿ” What is Encapsulation?

Encapsulation is the technique of wrapping data (fields) and code (methods) into a single unit and restricting direct access to some of the object's components.

✅ How Encapsulation is Achieved:

  • Using private fields
  • Exposing controlled access via public methods

๐Ÿงช Example:

public class BankAccount
{
    private decimal balance;

    public void Deposit(decimal amount)
    {
        if (amount > 0)
            balance += amount;
    }

    public decimal GetBalance()
    {
        return balance;
    }
}

The internal field balance cannot be accessed directly, providing better data protection.

๐Ÿ“Š Key Differences: Abstraction vs Encapsulation

Feature Abstraction Encapsulation
Definition Hides implementation details; shows only relevant features Hides data and internal state using access control
Purpose Reduce complexity Protect data integrity
Focus What the object does How data is accessed or modified
Achieved Using Interfaces, abstract classes Private fields, public methods
Real-World Analogy TV remote (user knows what buttons do, not how they work) ATM (securely encapsulates cash and logic inside)

๐Ÿง  Summary

Abstraction is about design — exposing the necessary behavior while hiding implementation logic.

Encapsulation is about security and control — hiding data and ensuring proper access through defined methods.

✅ When to Use What?

  • Use abstraction when designing reusable contracts and APIs.
  • Use encapsulation when you need to secure object state and enforce business rules.

In modern C# applications, both are used together to create clean, secure, and maintainable code structures.

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features