25 Feb 2024




Intermediate

Encapsulation in C# is achieved primarily through the use of access modifiers and properties. Encapsulation is one of the fundamental principles of object-oriented programming that allows you to hide the internal state of an object and only expose necessary functionalities to the outside world.

Here are some key mechanisms to achieve encapsulation in C#:

  1. Access Modifiers: C# provides access modifiers such as public, private, protected, internal, and protected internal. These modifiers control the visibility and accessibility of classes, methods, and other members within the program.

    • public: The member is accessible from any other code in the same assembly or another assembly that references it.
    • private: The member is accessible only within the same class or struct.
    • protected: The member is accessible within its class and by derived classes.
    • internal: The member is accessible within the same assembly, but not from another assembly.
    • protected internal: The member is accessible within the same assembly and by derived classes, even if they are in another assembly.
  2. Properties: Properties provide a way to encapsulate fields of a class by controlling access to them. They allow you to expose the state of an object while providing control over how that state can be modified or accessed.

    public class MyClass
    {
        private int myField;
    
        public int MyProperty
        {
            get { return myField; }
            set { myField = value; }
        }
    }
    

    Here, MyProperty provides controlled access to the myField field by using getter and setter methods.

  3. Encapsulation of Methods: Encapsulating methods by using appropriate access modifiers helps to control the access to behavior as well as data. Private methods are only accessible within the class and cannot be called from outside.

  4. Encapsulation through Interfaces: Interfaces define contracts for classes to implement. They help in achieving abstraction and encapsulation by hiding the implementation details of classes that implement the interface.

Encapsulation allows you to create classes that provide a clear and consistent interface to the outside world while hiding their internal state and implementation details. This helps in reducing complexity, improving maintainability, and promoting code reusability.

c-sharp
encapsulation