Encapsulation in C#
Encapsulation is one of the important principles of Object-Oriented Programming (OOP). It means keeping the data and the methods that work with that data together inside a class and controlling how that data can be accessed.
In simple words, Encapsulation means protecting data from direct unwanted access and providing controlled access to it.
What is Encapsulation?
Encapsulation is the process of wrapping data and the methods that operate on that data into a single unit, usually a class. It also allows us to control the visibility and modification of that data.
In C#, encapsulation is commonly implemented using access modifiers, properties, and methods.
Why Do We Need Encapsulation?
Suppose we have an Employee class and we allow anyone to directly change the employee's salary. This could result in invalid or unwanted data.
Encapsulation allows us to control how data is read and changed.
- Protects important data from unwanted direct access.
- Provides controlled access to class members.
- Allows validation before changing data.
- Makes code easier to maintain.
- Reduces accidental modification of data.
- Helps create secure and well-structured applications.
Access Modifiers in C#
Access modifiers determine where a class member can be accessed. They are an important part of implementing encapsulation.
| Access Modifier | Simple Meaning |
|---|---|
| public | Can be accessed from code that has access to the containing type. |
| private | Can be accessed only within the containing type. |
| protected | Can be accessed within the containing type and derived types. |
| internal | Can be accessed within the same assembly. |
Simple Encapsulation Example
Let's start with a simple example using a private field.
private string name;
public void SetName( string value)
{
name = value;
}
public string GetName()
{
return name;
}
}
The name field is private, so outside code cannot directly access it. Instead, the SetName() and GetName() methods provide controlled access.
Complete Program: Encapsulation
Now let's create a complete C# console program to understand encapsulation step by step.
using System;
class BankAccount
{
private double balance;
public void Deposit( double amount)
{
if (amount > 0)
{
balance += amount;
Console.WriteLine( "Amount deposited successfully.");
}
else
{
Console.WriteLine( "Amount must be greater than zero.");
}
}
public double GetBalance()
{
return balance;
}
}
class Program
{
static void Main()
{
BankAccount account = new BankAccount();
account.Deposit(5000);
Console.WriteLine( $"Current Balance: {account.GetBalance()}");
}
}
Program Output
Current Balance: 5000
Program Explanation
| Code | Explanation |
|---|---|
| class BankAccount | Creates a class named BankAccount. |
| private double balance; | Creates a private field named balance. Outside code cannot directly access it. |
| Deposit() | Provides a controlled way to add money to the account. |
| if (amount > 0) | Checks whether the amount is valid before changing the balance. |
| balance += amount | Adds the valid amount to the private balance. |
| GetBalance() | Provides controlled read access to the balance. |
| new BankAccount() | Creates an object of the BankAccount class. |
| account.Deposit(5000) | Calls the Deposit method and adds 5000 to the account. |
| account.GetBalance() | Gets the current balance through the public method. |
Why is the balance Field Private?
The balance field is private because we do not want outside code to directly change the account balance.
For example, without proper encapsulation, someone might try to do something like this:
This is not allowed because balance is private. The class controls how the balance can be changed through the Deposit() method.
Encapsulation with Validation
One major advantage of encapsulation is that we can validate data before allowing it to change.
{
if (amount > 0)
{
balance += amount;
}
else
{
Console.WriteLine( "Invalid amount.");
}
}
The validation ensures that a negative or zero amount cannot be deposited.
Encapsulation Using Properties
Properties are another common way to implement encapsulation in C#. We can control whether a property can be read or changed from outside the class.
public string Name { get; private set; }
public void SetStudentName( string name)
{
if (!string.IsNullOrWhiteSpace(name))
{
Name = name;
}
}
}
Here, Name can be read from outside the class, but its value can only be assigned from inside the Student class because the setter is private.
public get and private set
This pattern is frequently used when a value should be visible to other parts of the application but should not be freely changed from outside.
Other code can read StudentId, but cannot directly assign a new value to it. The class itself can control when and how the value changes.
Read-Only Data
Encapsulation can also be used to expose information without allowing external code to modify it.
public string EmployeeId { get; }
public Employee( string employeeId)
{
EmployeeId = employeeId;
}
}
The property can be read publicly, while its value is initialized inside the class.
Encapsulation vs Abstraction
Encapsulation and abstraction are related OOP concepts, but they are not exactly the same.
| Encapsulation | Abstraction |
|---|---|
| Focuses on protecting and controlling data. | Focuses on hiding unnecessary implementation details. |
| Commonly uses access modifiers and properties. | Commonly uses abstract classes and interfaces. |
| Controls how data is accessed or modified. | Shows only the required functionality. |
Example: Bank Account 📩👨🏫
A bank account is a good real-world example of encapsulation. The customer should not directly modify the internal balance. Instead, the bank system provides controlled operations such as deposit and withdrawal.
| Bank Concept | C# Concept |
|---|---|
| Account Balance | Private field |
| Deposit | Public method |
| Withdraw | Public method |
| Validation | Business rules inside methods |
Complete Program: Employee Salary
Let's take another practical example where salary is controlled through a method.
using System;
class Employee
{
private double salary;
public void SetSalary( double amount)
{
if (amount >= 15000)
{
salary = amount;
}
else
{
Console.WriteLine( "Salary must be at least 15000.");
}
}
public double GetSalary()
{
return salary;
}
}
class Program
{
static void Main()
{
Employee employee = new Employee();
employee.SetSalary(40000);
Console.WriteLine( $"Employee Salary: {employee.GetSalary()}");
}
}
Program Output
The salary field is private. The outside code cannot directly modify it. The SetSalary() method controls how salary is assigned and validates the value before storing it.
Benefits of Encapsulation
- Data Protection: Prevents direct unwanted modification.
- Validation: Allows validation before storing data.
- Maintainability: Internal implementation can change without changing how outside code uses the class.
- Control: Determines exactly how data can be accessed.
- Security: Helps protect important application data from inappropriate access.
- Reusability: Encapsulated classes can be reused across different parts of an application.
Encapsulation Best Practices
- Keep internal data private when direct access is not required.
- Use properties to expose data in a controlled manner.
- Validate important data before changing it.
- Keep business rules inside appropriate classes or services.
- Avoid exposing internal implementation unnecessarily.
- Give methods and properties meaningful names.
Common Beginner Mistakes
- Making every field public without considering whether direct access is necessary.
- Confusing encapsulation with simply making fields private.
- Forgetting to validate data before modifying important values.
- Exposing internal implementation unnecessarily.
- Putting unrelated responsibilities inside one class.
CIIT Practical Point
Encapsulation is used extensively in professional C# applications to protect business data and control how application components interact with each other.
In ASP.NET Core applications, models, services, repositories, and business components commonly use properties, private members, and methods to control application behavior.
During interviews, be ready to explain encapsulation with a real-world example such as a Bank Account or Employee Salary.
CIIT Interview Points
- What is encapsulation in C#?
- Why is encapsulation important?
- How can encapsulation be implemented in C#?
- What is the difference between public and private?
- Why should fields often be private?
- What is a property in C#?
- What is the purpose of private set?
- What is the difference between encapsulation and abstraction?
- Give a real-world example of encapsulation.
- How does encapsulation help with data validation?
Summary
- Encapsulation is an important principle of OOP.
- It combines related data and behavior inside a class.
- It helps control how data can be accessed or modified.
- Private members help hide internal data from direct outside access.
- Public methods and properties can provide controlled access.
- Validation can be performed before changing important data.
- Properties such as get; private set; are commonly used to control access.
- Encapsulation makes applications easier to maintain, understand, and protect.
Practice Questions
- Create a BankAccount class with a private balance field.
- Create a Deposit() method that accepts an amount.
- Add validation so negative amounts cannot be deposited.
- Create a GetBalance() method.
- Create an Employee class with a private salary field.
- Create a method to set salary with validation.
- Create a property using get; private set;.
- Explain encapsulation using an ATM example.