C# | Encapsulation

Encapsulation is defined as the wrapping up of data and information under a single unit. It is the mechanism that binds together the data and the functions that manipulate them. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield.

  • Technically in encapsulation, the variables or data of a class are hidden from any other class and can be accessed only through any member function of its own class in which they are declared.
  • As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
  • Encapsulation can be achieved by: Declaring all the variables in the class as private and using C# Properties in the class to set and get the values of variables.

Example: 

// C# program to illustrate encapsulation
using System;
  
public class DemoEncap {
  
    // private variables declared
    // these can only be accessed by
    // public methods of class
    private String studentName;
    private int studentAge;
  
    // using accessors to get and
    // set the value of studentName
    public String Name
    {
  
        get { return studentName; }
  
        set { studentName = value; }
    }
  
    // using accessors to get and
    // set the value of studentAge
    public int Age
    {
  
        get { return studentAge; }
  
        set { studentAge = value; }
    }
}
  
// Driver Class
class GFG {
  
    // Main Method
    static public void Main()
    {
  
        // creating object
        DemoEncap obj = new DemoEncap();
  
        // calls set accessor of the property Name,
        // and pass "Anmol" as value of the
        // standard field 'value'
        obj.Name = "
        Anmol& quot;
        ;
  
        // calls set accessor of the property Age,
        // and pass "21" as value of the
        // standard field 'value'
        obj.Age = 36;
  
        // Displaying values of the variables
        Console.WriteLine(" Name : " + obj.Name);
        Console.WriteLine(" Age : " + obj.Age);
    }
}

Output:

Name: Anmol
Age: 36

Explanation: 

In the above program, the “DemoEncap” class is encapsulated because the variables are declared private. To access these private variables, use the Name and Age accessors, which contain get and set methods to get and set the values ​​of private fields. Accessors are defined as public, so they can be accessed by other classes. 

Advantages of Encapsulation:

  • Data Hiding: The user will have no idea about the inner implementation of the class. It will not be visible to the user that how the class is stored values in the variables. He only knows that we are passing the values to accessors and variables are getting initialized to that value.
  • Increased Flexibility: We can make the variables of the class as read-only or write-only depending on our requirement. If we wish to make the variables as read-only then we have to only use Get Accessor in the code. If we wish to make the variables as write-only then we have to only use Set Accessor.
  • Reusability: Encapsulation also improves the re-usability and easy to change with new requirements.
  • Testing code is easy: Encapsulated code is easy to test for unit testing.

Encapsulation is a fundamental concept in object-oriented programming (OOP) that refers to the bundling of data and methods that process that data within a single unit. In C#, this is typically accomplished using classes.

The idea behind encapsulation is to hide the implementation details of a class from the outside world and expose only the public interfaces that allow users to interact with the class in a controlled and safe manner. This helps promote modularity, maintainability, and flexibility in the design of software systems.

To demonstrate encapsulation in C#, let’s consider the following example:


public class BankAccount {
    private decimal balance;
  
    public BankAccount(decimal initialBalance)
    {
        balance = initialBalance;
    }
  
    public void Deposit(decimal amount)
    {
        balance += amount;
    }
  
    public void Withdraw(decimal amount)
    {
        if (balance >= amount) {
            balance -= amount;
        }
        else {
            Console.WriteLine("Insufficient funds.");
        }
    }
  
    public decimal GetBalance() { return balance; }
}
  
class Program {
    static void Main(string[] args)
    {
        BankAccount myAccount = new BankAccount(1000);
  
        myAccount.Deposit(500);
        Console.WriteLine("Balance: "
                          + myAccount.GetBalance());
  
        myAccount.Withdraw(2200);
        Console.WriteLine("Balance: "
                          + myAccount.GetBalance());
    }
}

Output:

Balance: 1500
Insufficient funds.
Balance: 1500

In this example, we have a class BankAccount that represents a simple bank account with a balance that can be deposited and withdrawn.
Balance fields are marked as private, meaning they cannot be accessed directly from outside the class. Instead, it provides public methods Deposit, Withdraw, and GetBalance that provide a controlled interface to the balance field.

In the Main method, create an object myAccount of the BankAccount class with an initial balance of 1000. Next, call the Deposit and Withdraw methods to change the balance, and call the GetBalance method to retrieve the current balance. Note that the balance field cannot be accessed directly but must be manipulated using public methods provided by the class.

I hope you enjoyed reading this post. For more information you can check out Microsoft learn.

For more information you can visit our C# Section for more such posts.

Leave a Reply

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