C# encapsulation

https://‮w‬ww.theitroad.com

Encapsulation is an object-oriented programming concept that allows you to hide the implementation details of a class from the outside world and only expose a set of public interfaces. In C#, encapsulation is achieved using access modifiers, which control the level of access to the members of a class.

There are four access modifiers in C#:

  • public: The member is accessible from any code that can access the containing class.
  • private: The member is only accessible from within the containing class.
  • protected: The member is accessible from within the containing class and any derived classes.
  • internal: The member is accessible from any code in the same assembly, but not from other assemblies.

By default, members of a class are private, which means they can only be accessed from within the class. You can change the access level of a member by using one of the access modifiers.

Encapsulation allows you to control how the members of a class are used and accessed by other code. By making some members private, you can prevent other code from modifying or accessing them directly, which can help to improve the reliability and maintainability of your code. Instead, you can provide a set of public interfaces, such as properties or methods, that allow other code to interact with the class in a controlled way.

For example, consider the following class that uses encapsulation to hide its implementation details:

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; }
    }
}

In this class, the name and age fields are private, which means they cannot be accessed from outside the class. Instead, public properties (Name and Age) are used to expose the data to other code in a controlled way. This allows the class to maintain its internal state and ensure that it is used correctly.