What is Encapsulation in C# ?

What is Encapsulation in C# ?

To understand what encapsulation means, it can be considered as “surrounding” an entity, to keep and protect whatever is inside the surrounding.

It has a similar concept in programming as well, here encapsulation has a wider meaning than combining the members together within a class; it has a function of access restriction to the inner workings of that class as well.
Access modifiers implements Encapsulation. An access modifier defines the scope and visibility of a class member.
Encapsulation is also termed as information hiding.

C# supports the following access modifiers: public, private, protected, internal, protected internal.
Example of Encapsulation :
class Account
{
private double balance=0;
public void Deposit(double x)
{
balance += x;
}
public void Withdrawl(double x)
{
balance -= x;
}
public double FetchBalance()
{
return rembalance;
}
}
Key Points to Remember in this Code :
1. Hiding the rembalance member from the outside code.
2. Providing restricted access to it using public methods.
3. FetchBalance method can be modified only through the Deposit and Withdrawl methods.

We have a Control over the way data is accessed or modified.

Social Share

Leave a Reply

Your email address will not be published. Required fields are marked *