C# Encapsulation: Everything You Need to Know

If you are a C# developer, you must be familiar with the concept of encapsulation. Encapsulation is one of the fundamental pillars of object-oriented programming (OOP), which makes code more modular, secure, and maintainable. 

This article will discuss everything you need to learn about encapsulation in C#, including its definition, examples, benefits, and how to implement it in your code. So, if you want to learn more about encapsulation and how to incorporate it into your programming, keep reading.

csharp_encapsulation
C# Encapsulation

What is Encapsulation in C#?

Encapsulation is a mechanism in OOP that binds the data and its associated behaviour (methods) together in a single unit known as class. It is a technique of hiding the internal details of an object from the outside world and exposing only the necessary information or functionality to the user. 

In other words, encapsulation provides a way to protect the data from unauthorized access or modification and ensures that the object’s state remains consistent.

Encapsulation in C# is achieved through access modifiers (Example: public, private, protected, and internal) to restrict the visibility of the class members (fields, properties, methods, and events) from the outside world.
A class’s fields are typically marked as private, and its methods and properties are marked as public, protected, or internal based on the desired usage.

C# Encapsulation Example

Let’s take a simple example to understand how encapsulation works in C#. Suppose you have a class named BankAccount that contains one private field balance and two public methods “Deposit” and “Withdraw” to manipulate the balance.

using System;
public class BankAccount
{
    private decimal balance;
    public void Deposit(decimal amount)
    {
        balance += amount;
    }

    public void Withdraw(decimal amount)
    {
        if (balance < amount)
        {
            Console.WriteLine("Insufficient funds.");
            return;
        }     
            balance -= amount;
    }

    public decimal GetBalance()
    {
        return balance;
    }
}

class Program
{
    static void Main(string[] args)
    {
        BankAccount account = new BankAccount();
        account.Deposit(1000);
        account.Withdraw(500);
        decimal balance = account.GetBalance();
        Console.WriteLine("Account balance is: " + balance);
    }
}

In the above example, we can see that we can access the “Deposit” and “Withdraw” methods to modify the balance, but we cannot directly access the “balance” field.

We can use the GetBalance() method to retrieve the balance information.

Output:

Account balance is: 500

Why Do We Need Encapsulation?

Encapsulation provides several benefits to C# developers, some of which are listed below:

  • Security: Encapsulation provides a way to protect the data from unauthorized access or modification, making the code more secure and robust.
  • Modularity: Encapsulation promotes code modularity by grouping related data and behaviour into a single unit, making the code more organized and easier to maintain.
  • Abstraction: Encapsulation provides a way to abstract the implementation details of a class from the outside world, making it easier to understand and use the class without worrying about its internal implementation.
  • Flexibility: Encapsulation allows for changes to be made to the implementation of a class without affecting the code that uses the class. It makes the code more flexible and adaptable to changing requirements.
  • Code Reusability: Encapsulation promotes code reusability by allowing the same class to be used in multiple contexts without modifying its internal implementation.

How to Achieve Encapsulation in C#?

Encapsulation in C# can be achieved through the following techniques:

  • Access Modifiers: Access modifiers (public, private, protected, and internal) restrict the visibility of the class members from the outside world. Private members are only accessible within the same class, whereas public members are accessible from anywhere.
  • Properties: Properties provide a way to encapsulate the data by providing a controlled way of accessing and modifying the class members. Properties can have getter and setter methods that enforce validation and data consistency.
  • Interfaces: Interfaces provide a way to define a contract for a class without specifying its implementation details. It allows for loose coupling between classes and promotes code modularity and flexibility.

What is Abstraction and Encapsulation in C#?

Abstraction and encapsulation are two concepts in OOP that are often used together to promote code modularity and flexibility.

Abstraction is the process of hiding the implementation details of a class from the outside world and exposing only the essential features of the class. Abstraction is achieved through abstract classes and interfaces in C#.

Encapsulation, on the other hand, is the process of binding the data and its associated behaviour (methods) together in a single unit called a class. Encapsulation is achieved through access modifiers, properties, and interfaces in C#.

In summary, abstraction provides a way to define a contract for a class without specifying its implementation details, whereas encapsulation provides a way to hide the implementation details of a class from the outside world and expose only the necessary information or functionality.

Difference Between Abstraction and Encapsulation in C#

AbstractionEncapsulation
Abstraction is the process of hiding the implementation details of a class from the outside world and exposing only the essential features of the class.On the other hand, Encapsulation is the process of binding the data and its associated behaviour (methods) together in a single unit called a class.
Abstraction is achieved through abstract classes and interfaces in C#.Encapsulation is achieved through access modifiers, properties, and interfaces in C#.
Abstraction provides a way to define a contract for a class without specifying its implementation details.Encapsulation provides a way to hide the implementation details of a class from the outside world and expose only the necessary information or functionality.
Abstraction is used to achieve loose coupling between classes and promotes code modularity and flexibility.Encapsulation protects the data from unauthorized access or modification and ensures that the object’s state remains consistent.

Real-World Example of Encapsulation

Here is an example of encapsulation in C# with a real-world scenario:

Let’s say we have a Car class with fields such as make, model, year, and color. We also have a method called Start() that starts the car’s engine.

To implement encapsulation, we can make the fields private and expose them through public methods or properties also called getters and setters.

For example, we can have a public method called SetMake() that sets the value of a private field make and a public method called GetMake() that returns the value of the make field.

using System;
public class Car
{
    private string make;
    private string model;
    private int year;
    private string color;
    private bool isEngineOn;

    public void SetMake(string make)
    {
        // Add validation logic here
        this.make = make;
    }

    public string GetMake()
    {
        return make;
    }

    public void SetModel(string model)
    {
        // Add validation logic here
        this.model = model;
    }

    public string GetModel()
    {
        return model;
    }

    public void SetYear(int year)
    {
        // Add validation logic here
        this.year = year;
    }

    public int GetYear()
    {
        return year;
    }

    public void SetColor(string color)
    {
        // Add validation logic here
        this.color = color;
    }

    public string GetColor()
    {
        return color;
    }

    public void TurnOnEngine()
    {
        // Add error handling logic here
        isEngineOn = true;
        Console.WriteLine("Engine is on.");
    }

    public void TurnOffEngine()
    {
        isEngineOn = false;
        Console.WriteLine("Engine is off.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Car car = new Car();
        car.SetMake("Toyota");
        car.SetModel("Camry");
        car.SetYear(2023);
        car.SetColor("Blue");

        Console.WriteLine("Car make: " + car.GetMake());
        Console.WriteLine("Car model: " + car.GetModel());
        Console.WriteLine("Car year: " + car.GetYear());
        Console.WriteLine("Car color: " + car.GetColor());

        car.TurnOnEngine();
        car.TurnOffEngine();
    }
}

Output:

encapsulation example in csharp

References: MSDN-OOPs

FAQs

Q. What is Encapsulation in C#?

Encapsulation is a fundamental concept in object-oriented programming that refers to binding data and behaviour together in a single unit (i.e., a class) and controlling access to that unit.

Q. Why do we need Encapsulation in C#?

Encapsulation is important in C# because it promotes code modularity, flexibility, and maintainability. By encapsulating the data and behaviour of a class, you can ensure that it remains consistent throughout the lifetime of the object and that it can be easily modified and extended without affecting other parts of the code.

Q. What is the difference between Abstraction and Encapsulation in C#?

Abstraction refers to identifying the essential features of a concept and ignoring the non-essential ones.

Encapsulation, on the other hand, refers to binding the data and behaviour of a class together in a single unit and controlling access to that unit. While Encapsulation is often used to achieve Abstraction, they are not the same.

Q. How can I achieve Encapsulation in C#?

Encapsulation in C# can be achieved by using access modifiers such as private, protected, and public to control access to fields and methods,
using properties instead of public fields to provide controlled access to the data of a class, using interfaces to define the behaviour of a class and promote loose coupling, and using read-only and const fields to mark data as immutable and ensure consistency.

Recommended Articles:

Please share this post and let us know what you think in the comments.

c20e93cf99b4a0eb1e4a099de6c2c300?s=250&r=g
4 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments