Encapsulation in C#: Protecting Data

Encapsulation is a fundamental concept in C# that focuses on protecting data from unauthorized access and modification. In this guide, we'll explore the principles of encapsulation and how it helps ensure data integrity and code security.

What is Encapsulation?

Encapsulation is one of the four pillars of object-oriented programming (OOP) and involves bundling data (attributes) and methods (functions) that operate on that data into a single unit called a class. The key idea is to hide the internal details of the class and provide controlled access to its members.

Access Modifiers

C# uses access modifiers to control the visibility and accessibility of class members. The main access modifiers in C# are:

  • public: Members are accessible from any code that can access the class.
  • private: Members are only accessible within the class itself.
  • protected: Members are accessible within the class and its derived classes.
  • internal: Members are accessible within the same assembly.
  • protected internal: Members are accessible within the same assembly or derived classes.

Encapsulation in C#

Here's an example that demonstrates encapsulation:

public class BankAccount
private string accountNumber;
private decimal balance;
public BankAccount(string accountNumber)
this.accountNumber = accountNumber;
this.balance = 0;
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;
BankAccount myAccount = new BankAccount("123456789");
decimal currentBalance = myAccount.GetBalance();

In this example, the `accountNumber` and `balance` fields are private, meaning they can only be accessed within the `BankAccount` class. Public methods like `Deposit`, `Withdraw`, and `GetBalance` provide controlled access to the data, allowing you to protect the integrity of the account.

Benefits of Encapsulation

Encapsulation offers several benefits:

  • Protects data from unauthorized access and modification, enhancing data integrity and security.
  • Enables controlled access to data through well-defined methods, reducing the risk of errors and misuse.
  • Facilitates code maintenance and updates, as internal details can change without affecting external code that uses the class.


Encapsulation is a crucial concept in C# that helps protect data and maintain code integrity. By using access modifiers and defining public interfaces to interact with data, you can create more secure and maintainable code.

Practice using encapsulation in your C# programs to ensure data protection and code security. As you continue your programming journey, you'll explore more advanced topics in OOP and design patterns that leverage the principles of encapsulation.