Encapsulation
Encapsulation is used to hide its members from outside class or interface, whereas abstraction is used to show only essential features. In C# programming,Encapsulation uses five types of modifier to encapsulate data. These modifiers are public, private, internal, protected and protected internal.
Encapsulation is also called information hiding.
C# supports the following access modifiers: public, private, protected, internal, protected internal.
As seen in the previous examples, the public access modifier makes the member accessible from the outside of the class.
The private access modifier makes members accessible only from within the class and hides them from the outside.
protected will be discussed later in the course.
To show encapsulation in action, let’s consider the following example:
The Code:

The Output of Your Program:

We used encapsulation to hide the balance member from the outside code. Then we provided restricted access to it using public methods. The class data can be read through the GetBalance method and modified only through the Deposit and Withdraw methods.
You cannot directly change the balance variable. You can only view its value using the public method. This helps maintain data integrity.
We could add different verification and checking mechanisms to the methods to provide additional security and prevent errors.
In summary, the benefits of encapsulation are:
– Control the way data is accessed or modified.
– Code is more flexible and easy to change with new requirements.
– Change one part of code without affecting other parts of code.
