Keywords: Encapsulation in C#, OOP principles in C#, Data Hiding, Getters and Setters in C#, Access Modifiers, C# Encapsulation Example, Object-Oriented Programming in C#, Bank Account Example C#
π What is Encapsulation in C#?
Encapsulation is one of the four main pillars of Object-Oriented Programming (OOP) β along with inheritance, polymorphism, and abstraction.
In simple terms, encapsulation means hiding the internal state of an object and protecting it from unintended modification.
It helps in bundling data (fields) and methods (functions) that operate on that data into a single unit β a class.
This ensures data safety and improves code reliability.
π― Why Encapsulation is Important
Encapsulation helps you:
- β Protect sensitive data from unauthorized access
- β Control how data is accessed or modified
- β Prevent accidental changes to important variables
- β Improve flexibility and code maintainability
π§ Access Modifiers in C#
C# provides access modifiers to define the visibility of class members:
| Modifier | Description |
|---|---|
public | Accessible from anywhere |
private | Accessible only within the same class |
protected | Accessible within the class and its derived classes |
internal | Accessible within the same assembly/project |
The most common combination for encapsulation is private fields with public properties or methods.
π§± Private Fields with Getters and Setters
You can use private fields to store data securely, and getters and setters to control access.
πΉ Example 1: Manual Getters and Setters
class BankAccount
{
private double balance;
public double GetBalance()
{
return balance;
}
public void SetBalance(double amount)
{
if (amount >= 0)
balance = amount;
else
Console.WriteLine("Balance cannot be negative!");
}
}
Here, the balance field is private and can only be modified through the SetBalance() method β ensuring data safety.
βοΈ Auto-Implemented Properties
C# offers auto-properties for concise and cleaner code.
class BankAccount
{
public double Balance { get; private set; }
public void Deposit(double amount)
{
if (amount > 0)
Balance += amount;
}
public void Withdraw(double amount)
{
if (amount > 0 && amount <= Balance)
Balance -= amount;
}
}
Here, Balance can be read publicly but updated only within the class, thanks to the private set modifier.
π¦ Encapsulation Example: Bank Account with Balance Restrictions
Letβs implement a real-world scenario to understand encapsulation more deeply.
public class BankAccount
{
private double balance;
public BankAccount(double initialBalance)
{
if (initialBalance >= 0)
balance = initialBalance;
else
balance = 0;
}
public void Deposit(double amount)
{
if (amount > 0)
balance += amount;
else
Console.WriteLine("Invalid deposit amount!");
}
public void Withdraw(double amount)
{
if (amount > 0 && amount <= balance)
balance -= amount;
else
Console.WriteLine("Insufficient balance or invalid amount!");
}
public double GetBalance()
{
return balance;
}
}
public class Program
{
public static void Main()
{
BankAccount account = new BankAccount(1000);
account.Deposit(500);
account.Withdraw(200);
Console.WriteLine(account.GetBalance()); // Output: 1300
}
}
This example shows how encapsulation safeguards the balance by restricting direct access and enforcing validation logic through methods.
π§ Practice Exercise: Student Marks System
Try this small coding exercise to reinforce encapsulation concepts.
public class Student
{
private string name;
private int marks;
public Student(string studentName)
{
name = studentName;
}
public string GetName() => name;
public int GetMarks() => marks;
public void SetMarks(int value)
{
if (value >= 0 && value <= 100)
marks = value;
else
Console.WriteLine("Invalid marks! Please enter between 0 and 100.");
}
public void DisplayInfo()
{
Console.WriteLine($"Student Name: {name}");
Console.WriteLine($"Marks: {marks}");
}
}
Expected Output:
Student Name: Avni
Marks: 85
Invalid marks! Please enter between 0 and 100.
π§© Quick Quiz on Encapsulation
- What does encapsulation do in OOP?
β Protects data by restricting access - Which access modifier hides data from outside the class?
βprivate - Why are properties better than public fields?
β They allow validation and controlled access - What is an auto-property in C#?
β A property that automatically provides a getter and setter
π Conclusion
Encapsulation is the foundation of secure and maintainable C# code.
By keeping data private and exposing it through controlled public methods or properties, you:
- Enforce rules and logic at one place
- Prevent invalid states
- Make your code cleaner and safer
Whether youβre designing a banking system or a simple student management app, encapsulation ensures your classes remain reliable, consistent, and professional.