Open In App

Encapsulation in C#

Last Updated : 17 Sep, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Encapsulation is one of the core principles of object-oriented programming (OOP). It refers to the practice of binding data (fields) and the methods that operate on that data into a single unit, while restricting direct access to some components. This ensures controlled interaction with an object’s internal state.

ecapsulation
Encapsulation

Key Concepts

  • Encapsulation hides the internal representation of an object and exposes only necessary operations.
  • Fields are often kept private while access is provided through public properties or methods.
  • It improves data security, code maintainability and flexibility.
  • Access modifiers (private, public, protected, internal) control visibility of members.

Example:

C#
using System;

class Account
{
    private double balance; // hidden field

    public void Deposit(double amount)
    {
        if (amount > 0)
            balance += amount;
    }

    public void Withdraw(double amount)
    {
        if (amount <= balance)
            balance -= amount;
    }

    public double GetBalance()
    {
        return balance;
    }
}

class GFG
{
    static void Main()
    {
        Account acc = new Account();
        acc.Deposit(500);
        acc.Withdraw(200);
        Console.WriteLine("Balance: " + acc.GetBalance());
    }
}

Output
Balance: 300

Explanation:

  • balance is private and cannot be accessed directly from outside.
  • The class provides controlled methods (Deposit, Withdraw, GetBalance) to interact with the field.

Encapsulation Using Properties

C# provides properties to simplify encapsulation, acting like smart getters and setters.

C#
using System;

class Student
{
    private string name; // private field

    public string Name
    {
        get { return name; }
        set 
        { 
            if (!string.IsNullOrEmpty(value))
                name = value; 
        }
    }
}
class Program
{
    static void Main()
    {
        Student s = new Student();
        s.Name = "Alex";
        Console.WriteLine("Student Name: " + s.Name);
    }
}

Output
Student Name: Alex

Explanation:

  • The field name is private.
  • The Name property controls how values are set and retrieved.
  • This improves flexibility compared to public fields.

Advantages

  • Data Protection: Prevents unauthorized access to fields.
  • Controlled Access: Exposes only required operations.
  • Code Flexibility: Internal implementation can change without affecting external code.
  • Maintainability: Reduces coupling between classes.

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.

Article Tags :

Explore