Open In App

C# Encapsulation

Last Updated : 29 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Encapsulation in C# is the process of wrapping data and methods that operate on that data within a single unit. It is the mechanism that binds together the data and the functions that manipulate them. It acts as a protective shield that prevents direct access to the internal representation of an object. This ensures that an object’s internal state cannot be changed arbitrarily from outside the class.

Key Concepts of Encapsulation:

  • 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 class in which they are declared.
  • As the data in a class is hidden from other classes, 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 the variables.

Below is the diagrammatic representation of the encapsulation concept for better understanding:


Now let's go through a simple example to understand the concept practically.

Example:

C#
// Demonstration of Encapsulation
using System;

public class Geeks 
{
    // private variables declared
    // can accessed by
    // public methods of class
    private String studentName;
    private int studentAge;

    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; }
    }
}

class GFG
{
    static public void Main()
    {
        Geeks obj = new Geeks();

        // calls set accessor of the property Name,
        // and pass value
        obj.Name = "Ankita";

        // calls set accessor of the property Age,
        // and pass "21" as value of the
        // standard field 'value'
        obj.Age = 21;

        // Displaying values
        Console.WriteLine(" Name: " + obj.Name);
        Console.WriteLine(" Age: " + obj.Age);
    }
}

Output
 Name: Ankita
 Age: 21

Explanation: In the above program, the class Geeks is encapsulated as the variables are declared as private. To access these private variables we are using the Name and Age accessors which contain the get and set method to retrieve and set the values of private fields. Accessors are defined as public so that they can access other classes.


Lets's take another example;

Example:

C#
// Demonstration of Encapsulation
using System;

public class BankAccount 
{
    private decimal balance;

  	// Constructor
    public BankAccount(decimal initialBalance)
    {
        balance = initialBalance;
    }

  	// Deposit Method
    public void Deposit(decimal amount)
    {
        balance += amount;
    }

  	// Withdraw Method
    public void Withdraw(decimal amount)
    {
        if (balance >= amount) {
            balance -= amount;
        }
        else {
            Console.WriteLine("Insufficient funds.");
        }
    }

  	// Check the Balance of Account
    public decimal GetBalance() { 
      	return balance; 
    }
}

class Program 
{
    static void Main(string[] args)
    {
      	// Create new Bank Account
        BankAccount myAccount = new BankAccount(1000);

        myAccount.Deposit(500);
        Console.WriteLine("Balance: " + myAccount.GetBalance());

        myAccount.Withdraw(2000);
        Console.WriteLine("Balance: " + myAccount.GetBalance());
    }
}

Output
Balance: 1500
Insufficient funds.
Balance: 1500

Explanation: In the above example, we can not access the private variable directly and they are hidden. we can only perform the operation using methods like Withdraw(), GetBalance() etc. We create an Myaccount of the BankAccount class with an initial balance of 1000. We then call the Deposit and Withdraw methods to modify the balance, and the GetBalance() method to retrieve the current balance.

Note: We cannot access the balance field directly, but must use the public methods provided by the class to interact with it.

Advantages

  • The user has no idea about the inner implementation of the class. Hidden from user that how the class is stored values in the variables. User can only access the response only through the accessor methods.
  • 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.
  • Encapsulation also improves the re-usability and easy to change with new requirements.
  • Encapsulated code is easy to test for unit testing.

Disadvantages

  • Using getters and setters adds extra code compared to accessing fields directly.
  • Accessing data through methods may be a bit slower than direct access.
  • Since data is hidden, it can sometimes be difficult to quickly inspect or change values during debugging.

Next Article
Article Tags :

Similar Reads