0
0
CsharpConceptBeginner · 3 min read

Encapsulation in C#: What It Is and How It Works

In C#, encapsulation is the practice of hiding the internal details of a class and exposing only what is necessary through public methods or properties. It helps protect data by controlling how it is accessed or changed, keeping the class safe from unintended interference.
⚙️

How It Works

Think of encapsulation like a protective box around your data and code inside a class. You decide what parts of the box can be seen or touched from outside. This means you keep the important details hidden and only show what others need to use.

For example, if you have a class representing a bank account, you don’t want anyone to change the balance directly. Instead, you provide methods like Deposit or Withdraw that control how the balance changes. This keeps the data safe and consistent.

In C#, you use access modifiers like private to hide fields and public to allow controlled access through methods or properties. This way, the class controls its own data and behavior.

💻

Example

This example shows a BankAccount class that hides its balance and only allows changes through methods.

csharp
public class BankAccount
{
    private decimal balance; // hidden data

    public BankAccount(decimal initialBalance)
    {
        balance = initialBalance;
    }

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

    public void Withdraw(decimal amount)
    {
        if (amount > 0 && amount <= balance)
        {
            balance -= amount;
        }
    }

    public decimal GetBalance()
    {
        return balance;
    }
}

class Program
{
    static void Main()
    {
        BankAccount account = new BankAccount(100);
        account.Deposit(50);
        account.Withdraw(30);
        System.Console.WriteLine(account.GetBalance());
    }
}
Output
120
🎯

When to Use

Use encapsulation whenever you want to protect important data inside your classes and control how it changes. It is especially useful in real-world programs where data integrity matters, like banking, inventory systems, or user profiles.

Encapsulation helps prevent bugs by stopping outside code from changing data in unexpected ways. It also makes your code easier to maintain because you can change the internal details without affecting other parts of the program.

Key Points

  • Encapsulation hides internal data using private fields.
  • It exposes safe ways to access or modify data through public methods or properties.
  • It protects data integrity and prevents unintended changes.
  • It makes code easier to maintain and understand.

Key Takeaways

Encapsulation hides class data and controls access through methods or properties.
Use private fields to protect data and public methods to allow safe changes.
It helps keep your program’s data safe and consistent.
Encapsulation makes your code easier to maintain and less error-prone.