CAB201

icon picker
Encapsulation

Encapsulation in C#: A Quick Guide

Encapsulation is one of the fundamental principles of object-oriented programming (OOP). It involves bundling the data (variables) and the methods that operate on the data into a single unit, known as a class. Encapsulation also restricts direct access to some of an object's components, which can prevent the accidental modification of data.

Key Concepts

Data Hiding

Encapsulation allows you to hide the internal state of an object and only expose a controlled interface for interacting with that data. This is achieved using access modifiers.
Private: Members are accessible only within the same class.
Public: Members are accessible from any other code.
Protected: Members are accessible within the same class and by derived class instances.
Internal: Members are accessible within the same assembly.

Accessors and Mutators

Also known as getters and setters, these methods allow controlled access to private fields.
public class Person
{
private string name;

public string GetName()
{
return name;
}

public void SetName(string value)
{
if (!string.IsNullOrEmpty(value))
{
name = value;
}
}
}

Properties

Properties provide a more concise way to define accessors and mutators in C#. They can be used to encapsulate a field and provide validation logic.
public class Person
{
private string name;

public string Name
{
get { return name; }
set
{
if (!string.IsNullOrEmpty(value))
{
name = value;
}
}
}
}

Benefits of Encapsulation

Control: Encapsulation provides control over the data by allowing you to define how external code can interact with it.
Flexibility and Maintenance: Changes to the implementation can be made without affecting external code that uses the class.
Security: Encapsulation helps protect the integrity of the data by preventing unauthorized or unintended modifications.

Example

public class BankAccount
{
private decimal balance;

public decimal Balance
{
get { return balance; }
private set
{
if (value >= 0)
{
balance = value;
}
}
}

public void Deposit(decimal amount)
{
if (amount > 0)
{
Balance += amount;
}
}

public void Withdraw(decimal amount)
{
if (amount > 0 && amount <= balance)
{
Balance -= amount;
}
}
}

// Usage
BankAccount account = new BankAccount();
account.Deposit(100);
account.Withdraw(50);
Console.WriteLine($"Balance: {account.Balance}"); // Output: Balance: 50

Summary

Encapsulation: Bundles data and methods within a class, restricting access to the internals of that class.
Access Modifiers: Control visibility and access to class members.
Properties: Provide a clean and controlled way to access and modify private fields.
Benefits: Enhances control, flexibility, security, and maintainability of code.
Encapsulation is a powerful tool in OOP that helps ensure that your classes are used correctly and remain robust over time.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.