An Overview of C# Encapsulation

C# programming examples

Encapsulation is one of the striking features of object-oriented programming (OOP) that enables programmers to hide the internal details of an object while providing a well-defined interface for interacting with it.

This programming tutorial will discuss encapsulation, its benefits and how it can be implemented in C#.

Before reading further – if you are new to OOP software development in C#, or want to refresh your memory, we have a few tutorials we recommend checking out:

What is Encapsulation in C#?

Encapsulation refers to hiding an object’s internal implementation details from the outside world while exposing only the essential information. It allows developers to design classes with an interface for interacting with other code while protecting the internal data and implementation from external interference.

Encapsulation has several benefits, including improving code maintainability by making it easier to modify and extend without affecting other system parts. It also enhances the security and reliability of code by limiting external access to sensitive data and enforcing business rules and constraints.

Encapsulation in C# is achieved by taking advantage of the access modifiers that include public, private protected, private, internal, and protected that control their visibility and accessibility of the members of a class.

By making data members private and exposing them only through public methods or properties, encapsulation allows developers to prevent external code from directly manipulating the object’s data and ensures that any changes to the internal implementation can be made without affecting other parts of the system.

Since the members of a class are private by default in OOP languages such as Java and C#, you can only access them within the class. By using the public modifier, a member can be made accessible from outside the class. Encapsulation promotes data integrity and security and allows for easier maintenance and evolution of the codebase.

You can learn more about class members in our tutorial: Class Members in C#.

How to Implement Encapsulation Using Access Modifiers in C#

In this section we will take a look at some examples of encapsulation using access modifiers in C#.

Consider the following code example that shows a class containing public members:

public class Rectangle
{
    public double Width { get; set; }
    public double Height { get; set; }

    public Rectangle(double width, double height)
    {
        Width = width;
        Height = height;
    }
    public double Area()
    {
        return Width * Height;
    }
    public double Perimeter()
    {
        return 2 * (Width + Height);
    }
}

In this C# code example, the Rectangle class has two public members – Width and Height. These members are accessible from outside the class and can be read and written directly. The class provides the public methods Area() and Perimeter() to allow outside code to interact with the object.

Hence, in this class design, the data members of the class are not encapsulated from the external world.

The following is a code example that shows a class that contains private members in C#:

public class Account
{
    private string accountNumber;
    private decimal balance;
    public Account(string accountNumber, decimal balance)
    {
        this.accountNumber = accountNumber;
        this.balance = balance;
    }
    public decimal GetBalance()
    {
        return balance;
    }
    public void Deposit(decimal amount)
    {
        balance += amount;
    }
    public void Withdraw(decimal amount)
    {
        if (balance >= amount)
        {
            balance -= amount;
        }
    }
}

In this example, the Account class has two private members: accountNumber and balance. These members are not accessible from outside the class. The class provides public methods GetBalance(), Deposit(), and Withdraw() to allow outside code to interact with the object.

Read: Top Tools for Remote Developers

The following code example illustrates a class that comprises protected members:

public class Animal
{
    protected string name;
    protected int age;
    public Animal(string name, int age)
    {
        this.name = name;
        this.age = age;
    }
    public virtual void MakeSound()
    {
       Console.WriteLine("Inside the MakeSound method of Animal class…");
    }
}
public class Tiger : Animal
{
    public Tiger(string name, int age) : base(name, age)
    {
    }
    public override void MakeSound()
    {
      Console.WriteLine("Inside the MakeSound method of the Tiger class…");
    }
}

In this code example, the Animal class has two protected members: name and age. These members are accessible from derived classes like Tiger, but not from outside the class hierarchy. The Animal class provides a virtual method named MakeSound() that can be overridden by the derived classes, such as the Tiger class.

How to Implement Encapsulation Using Properties in C#

The code example given below shows a class with private data members exposed to the external world using corresponding public properties in C#:

public class Person
{
    private string name;
    private int age;
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    public int Age
    {
        get { return age; }
        set { age = value; }
    }
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

In this example, the Person class has two private fields: name and age, and two public properties – Name and Age. The properties provide encapsulation by allowing outside code to read and write the private fields indirectly, rather than accessing them directly. This allows the class to control access to the fields and enforce business rules if necessary.

The following code example shows a class that contains read-only properties in C#:

public class Circle
{
    private readonly double radius;
    public Circle(double radius)
    {
        this.radius = radius;
    }
    public double Radius
    {
        get { return radius; }
    }
    public double Area
    {
        get { return Math.PI * radius * radius; }
    }
}

In this example, the Circle class has a private field radius and two public read-only properties – Radius and Area. The read-only properties provide encapsulation by allowing outside code to read the private field but not modify it. This ensures that the Circle object remains immutable, makes your data secure and enforces encapsulation.

Use Cases and Benefits of Encapsulation in C#

Some of the common use cases and benefits of encapsulation include data integrity, increased security, reusable code, easier testing, and modularity, as well as the following:

  • Security and data integrity: Encapsulation provides a layer of security and data integrity by preventing unauthorized access and modification of data. By making class members private and exposing them via only a well-defined interface, encapsulation ensures that the internal workings of an object are hidden from outside code. This helps to prevent bugs, errors, and security vulnerabilities caused by direct access to internal data.
  • Abstraction and modularity: Encapsulation facilitates better abstraction and modularity in code. By encapsulating complex logic in well-defined objects, developers can abstract away implementation details and focus on high-level functionality. As a result of this, the code becomes easier to read and maintain over time, and it is also simpler to modify.
  • Code reuse: Encapsulation promotes code reuse by making it easy to reuse objects in different parts of the codebase. By exposing a well-defined interface, objects can be used by other parts of the codebase without needing to know about their internal implementation.
  • Testing: Encapsulation makes testing easier by allowing developers to test objects in isolation from the rest of the codebase. By encapsulating logic in well-defined objects with well-defined interfaces, developers can create isolated test cases for individual objects and test them independently.
  • Flexibility and maintenance: Encapsulation can also improve code organization, flexibility and maintenance by providing a way to optimize internal implementation without affecting external code. By encapsulating implementation details, developers can change the internal implementation of an object without affecting other parts of the codebase.

Final Thoughts on C# Encapsulation

Encapsulation helps developers write more secure, maintainable, and extensible code. By carefully choosing which members to expose and which not to, encapsulation helps to ensure that the class remains maintainable, reusable, and extensible. When you need to alter the implementation of a class, you can often use encapsulation to make sure that you do not affect the clients of the class that depends on it for its functionality.

To further your understanding of OOP concepts in C#, we recommend checking out our tutorials:

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read