Encapsulation in C# Language
Encapsulation is one of the fundamental principles of object-oriented programming (OOP), and it plays a crucial role in the
Encapsulation is one of the fundamental principles of object-oriented programming (OOP), and it plays a crucial role in the
Encapsulation is one of the four pillars of OOP, the others being inheritance, polymorphism, and abstraction. It is the practice of bundling the data (attributes) and the methods (functions) that operate on the data into a single unit known as a class. In C#, encapsulation is achieved through access modifiers and properties.
C# provides several access modifiers that control the visibility and accessibility of class members. The common access modifiers include:
Let’s consider an example of encapsulation using a simple class representing a bank account. We’ll use access modifiers to protect the data and provide controlled access to it:
using System;
public class BankAccount
{
private string accountHolder;
private double balance;
public BankAccount(string holderName, double initialBalance)
{
accountHolder = holderName;
balance = initialBalance;
}
public void Deposit(double amount)
{
if (amount > 0)
balance += amount;
}
public void Withdraw(double amount)
{
if (amount > 0 && balance >= amount)
balance -= amount;
}
public double GetBalance()
{
return balance;
}
}
class Program
{
static void Main()
{
BankAccount myAccount = new BankAccount("John Doe", 1000.0);
myAccount.Deposit(500.0);
myAccount.Withdraw(200.0);
// You cannot access private members directly from outside the class.
// Uncommenting the line below would result in a compilation error.
// myAccount.balance = 5000;
double balance = myAccount.GetBalance();
Console.WriteLine("Account balance for " + myAccount.GetAccountHolder() + ": " + balance);
}
}
In this example, we encapsulated the accountHolder
and balance
fields by marking them as private. This ensures that these fields can only be accessed through the public methods provided by the BankAccount
class, such as Deposit
, Withdraw
, and GetBalance
. This encapsulation protects the data from being accidentally or maliciously manipulated from outside the class.
Subscribe to get the latest posts sent to your email.