How can we implement Encapsulation in C#?
Encapsulation in C# using Accessors and Mutators:
Let us see an example to understand this concept. In the following example, we declare the balance variable as private in the Bank class, and hence it can not be accessed directly outside of the Bank class. In order to access this balance variable, we have exposed two public methods i.e. get balance and set the balance. The getBalance method (Accessors) is used to fetch the value stored in the balance variable whereas the set balance method (Mutator) is used to set the value in the balance variable.
public class HDFCBank
//hiding class data by declaring the variable as private
private double balance;
//creating public setter and getter methods
public double getBalance()
//add validation logic if needed
public void setBalance(double balance)
// add validation logic to check whether data is correct or not
this.balance = balance;
public static void Main()
HDFCBank hDFCBank = new HDFCBank();
Console.WriteLine("Press any key to exist.");