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:

ModifierAccessibility
publicAccessible from anywhere (inside/outside the class)
privateAccessible only within the class (default for fields)
protectedAccessible within the class and derived classes
internalAccessible within the same assembly/project
protected internalAccessible in derived classes or same assembly
private protectedAccessible 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

  1. Data Protection β†’ Prevent invalid or inconsistent data

  2. Abstraction β†’ Hide internal details, expose only necessary methods/properties

  3. Maintainability β†’ Internal implementation can change without affecting users

  4. 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 ModifierScope/AccessUse Case
publicAnywhereExpose safe API
privateOnly within classProtect internal data
protectedWithin class & derived classesAllow inheritance access
internalSame assemblyProject-wide access
protected internalDerived class or same assemblyFlexible inheritance within project
private protectedDerived class in same assemblyTight 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