Letβs go through encapsulation in C# β one of the core principles of object-oriented programming (OOP).
π 1. What is Encapsulation?
Encapsulation is the practice of restricting direct access to a classβs internal data and exposing it safely through methods or properties.
-
Keeps fields private
-
Provides controlled access via public/protected methods or properties
-
Protects internal state of the object
π 2. Access Modifiers in C#
Encapsulation in C# is implemented using access modifiers:
Modifier | Accessibility |
---|---|
public | Accessible from anywhere (inside/outside the class) |
private | Accessible only within the class (default for fields) |
protected | Accessible within the class and derived classes |
internal | Accessible within the same assembly/project |
protected internal | Accessible in derived classes or same assembly |
private protected | Accessible in derived classes within the same assembly |
π 3. Example: Encapsulation with Fields and Properties
public class Person
{
// Private field - not accessible directly
private int age;
// Public property to control access
public int Age
{
get { return age; }
set
{
if (value >= 0) // Validation
age = value;
else
Console.WriteLine("Age cannot be negative");
}
}
// Public method
public void Display()
{
Console.WriteLine($"Age: {Age}");
}
}
// Usage
Person person = new Person();
person.Age = 25; // Calls set accessor
person.Display(); // Age: 25
person.Age = -5; // Age cannot be negative
-
age
is private β cannot be modified directly -
Age
property provides controlled access β encapsulation
π 4. Why Encapsulation is Important
-
Data Protection β Prevent invalid or inconsistent data
-
Abstraction β Hide internal details, expose only necessary methods/properties
-
Maintainability β Internal implementation can change without affecting users
-
Reusability β Safe and predictable object behavior
π 5. Example: Protected Modifier
public class Animal
{
protected string species;
public void SetSpecies(string name)
{
species = name;
}
}
public class Dog : Animal
{
public void PrintSpecies()
{
Console.WriteLine($"Species: {species}"); // Accessible because protected
}
}
// Usage
Dog dog = new Dog();
dog.SetSpecies("Canine");
dog.PrintSpecies(); // Species: Canine
species
is protected β accessible in derived class (Dog
) but not outside
π 6. Summary Table
Access Modifier | Scope/Access | Use Case |
---|---|---|
public | Anywhere | Expose safe API |
private | Only within class | Protect internal data |
protected | Within class & derived classes | Allow inheritance access |
internal | Same assembly | Project-wide access |
protected internal | Derived class or same assembly | Flexible inheritance within project |
private protected | Derived class in same assembly | Tight control with inheritance |
β Tip:
-
Always keep fields private and expose them via properties
-
Use protected for members that should be available to subclasses
-
Encapsulation improves safety, maintainability, and readability