C# Encapsulation

Encapsulation is one of the fundamental principles of object-oriented programming (OOP), and it refers to the bundling of data and methods (or functions) that operate on that data within a single unit called a class. C# provides various mechanisms to achieve encapsulation, primarily through access modifiers and properties.

Access Modifiers in C#: C# has four access modifiers that control the accessibility of members (fields, properties, methods, etc.) within a class. These access modifiers are:

  1. Public: Members marked as public are accessible from any code that can access the class. They have the widest accessibility.
  2. Private: Members marked as private are accessible only within the same class. They are not accessible from outside the class, including derived classes.
  3. Protected: Members marked as protected are accessible within the same class and its derived classes. They are not accessible from outside the class hierarchy.
  4. Internal: Members marked as internal are accessible within the same assembly (a .dll or .exe file). They are not accessible from outside the assembly.

Properties in C#: Properties provide a way to encapsulate fields by providing controlled access to them. Properties encapsulate the logic for getting (reading) and setting (writing) values of private fields, allowing us to enforce validation, calculations, or any other custom logic.

Here’s an example demonstrating encapsulation using properties in C#:

public class Person
    private string name;
    private int age;

    public string Name
        get { return name; }
        set { name = value; }

    public int Age
        get { return age; }
        set { age = value; }

public class Program
    static void Main()
        Person person = new Person();
        person.Name = "John Doe";
        person.Age = 25;

        Console.WriteLine("Name: " + person.Name);
        Console.WriteLine("Age: " + person.Age);

In the example above, the fields name and age are encapsulated within the Person class. The properties Name and Age provide controlled access to these private fields, allowing us to get and set their values. The logic within the property accessors can be expanded to perform additional operations like validation, calculations, or triggering events.

Encapsulation helps in achieving data hiding, abstraction, and modularity, which in turn promotes better code organization, reusability, and maintainability in object-oriented programming.