C# Encapsulation Explained: OOP Concept with Examples
Encapsulation in C# is an Object-Oriented Programming (OOP) concept that means wrapping data (variables) and methods into a single unit (class) and restricting direct access to some of the object’s components.
In simple terms, encapsulation helps protect data from outside interference and misuse by controlling how it is accessed or modified.
1. What is Encapsulation in C#?
Encapsulation is:
• Binding data and methods together in a class
• Hiding internal details of how data is stored
• Controlling access using access modifiers (private, public, protected)
2. How Encapsulation Works
Encapsulation is achieved using:
• Private fields
• Public properties (getters/setters)
3. Example of Encapsulation in C#
using System;
class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void Main()
{
Person p = new Person();
p.Name = "John";
Console.WriteLine(p.Name);
}
}
4. Why Use Encapsulation?
Advantages:
• Data security (prevents direct access)
• Controlled access to variables
• Better maintainability
• Flexibility to change internal implementation
• Improves code structure
5. Real-World Example
Think of encapsulation like a bank account:
• You cannot directly access bank balance
• You must use methods (ATM, app, bank system)
• Bank controls how money is accessed or modified
6. Access Modifiers in Encapsulation
| Modifier | Description |
|---|---|
| private | Accessible only inside the class |
| public | Accessible from anywhere |
| protected | Accessible in class and derived classes |
| internal | Accessible within the same project |
7. Encapsulation with Validation (Best Practice)
class Student
{
private int age;
public int Age
{
get { return age; }
set
{
if (value > 0)
age = value;
}
}
}
This ensures invalid data cannot be assigned.
8. Common Mistakes
• Using public fields instead of private fields
• Not using validation in setters
• Confusing encapsulation with abstraction
• Exposing internal data unnecessarily
9. Encapsulation vs Abstraction
| Encapsulation | Abstraction |
|---|---|
| Hides data using access modifiers | Hides implementation details |
| Focuses on data protection | Focuses on hiding complexity |
| Achieved using classes | Achieved using abstract classes/interfaces |
10. Best Practices
• Always use private fields
• Use public properties for controlled access
• Add validation in setters
• Avoid exposing internal variables directly
• Keep class responsibilities clear