Encapsulation is a core principle of object-oriented programming in C#. It involves bundling data and methods that operate on that data within a single unit or object. This concept helps in hiding the internal details of how an object works, providing a clean and well-defined interface for interacting with the object.
Data hiding is achieved by declaring fields as private, making them inaccessible from outside the class. This prevents direct manipulation of an object's state, ensuring data integrity.
C# provides various access modifiers to control the visibility of class members:
private
: Accessible only within the same classpublic
: Accessible from anywhereprotected
: Accessible within the same class and derived classesinternal
: Accessible within the same assemblyProperties provide a way to access and modify private fields while maintaining encapsulation. They allow you to add logic for getting and setting values, such as validation or computation.
Let's look at an example of how to implement encapsulation in C#:
public class BankAccount
{
private decimal balance;
public string AccountHolder { get; set; }
public decimal Balance
{
get { return balance; }
private set { balance = value; }
}
public void Deposit(decimal amount)
{
if (amount > 0)
{
balance += amount;
}
}
public bool Withdraw(decimal amount)
{
if (amount > 0 && balance >= amount)
{
balance -= amount;
return true;
}
return false;
}
}
In this example, the balance
field is private, preventing direct access from outside the class. The Balance
property provides read-only access to the balance, while the Deposit
and Withdraw
methods control how the balance can be modified.
Encapsulation is closely related to other object-oriented programming principles in C#:
Understanding encapsulation is crucial for writing robust and maintainable C# code. It forms the foundation for creating well-structured classes and promotes good software design practices.