Encapsulation in C#
Introduction
Encapsulation is one of the fundamental principles of object-oriented programming (OOP). It is the concept of wrapping data (variables) and methods (functions) into a single unit known as a class. Encapsulation helps in protecting the data from unauthorized access and modification. In C#, encapsulation is implemented using access modifiers like private
, public
, protected
, and internal
.
Access Modifiers
Access modifiers are keywords used to define the accessibility of classes, methods, and variables. Here are the most commonly used access modifiers in C#:
public
: The member is accessible from any other class.private
: The member is accessible only within the same class.protected
: The member is accessible within the same class and by derived class instances.internal
: The member is accessible within the same assembly, but not from another assembly.
Getters and Setters
Getters and setters are special methods that provide a way to access and update the value of a private variable. They are used to implement encapsulation in C#. Here is an example:
public class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
In the above example, the name
variable is private, but it can be accessed and modified using the Name
property, which has a getter and a setter.
Benefits of Encapsulation
Encapsulation provides several benefits:
- Data Hiding: Encapsulation hides the internal state of an object from the outside world. This helps in protecting the data from unauthorized access and modification.
- Modularity: Encapsulation makes the code more modular. Each class has a specific responsibility, which makes it easier to manage and maintain the code.
- Flexibility: Encapsulation allows the internal implementation of a class to be changed without affecting the code that uses the class.
- Reusability: Encapsulation promotes code reusability. Classes can be reused in different programs or projects without modification.
Practical Example
Let's consider a practical example of encapsulation in C#. We will create a class called BankAccount
that represents a bank account. The class will have private variables for the account number and balance, and public methods to deposit and withdraw money, and check the balance.
using System;
public class BankAccount
{
private string accountNumber;
private double balance;
public BankAccount(string accountNumber, double initialBalance)
{
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
public void Deposit(double amount)
{
if (amount > 0)
{
balance += amount;
Console.WriteLine($"Deposited: {amount:C}");
}
else
{
Console.WriteLine("Deposit amount must be positive.");
}
}
public void Withdraw(double amount)
{
if (amount > 0 && amount <= balance)
{
balance -= amount;
Console.WriteLine($"Withdrew: {amount:C}");
}
else
{
Console.WriteLine("Insufficient funds or invalid amount.");
}
}
public double GetBalance()
{
return balance;
}
}
class Program
{
static void Main()
{
BankAccount account = new BankAccount("123456789", 500.0);
account.Deposit(150.0);
account.Withdraw(50.0);
Console.WriteLine($"Current Balance: {account.GetBalance():C}");
}
}
In this example, the accountNumber
and balance
variables are private, which means they cannot be accessed directly from outside the class. The Deposit
, Withdraw
, and GetBalance
methods provide controlled access to these variables. This ensures that the balance cannot be set to an invalid value directly, thus maintaining the integrity of the data.
Deposited: $150.00 Withdrew: $50.00 Current Balance: $600.00
Conclusion
Encapsulation is a key concept in object-oriented programming that helps in protecting data and making the code more modular, flexible, and reusable. By using access modifiers and properties (getters and setters), you can control how the data in your classes is accessed and modified. This tutorial provided an overview of encapsulation in C# with detailed explanations and examples. Understanding and applying encapsulation will help you write better and more maintainable code.