Mark As Completed Discussion

Encapsulation

Encapsulation is one of the fundamental principles of object-oriented programming. It is the practice of hiding internal implementation details and exposing only the necessary information and functionality to the outside world. Encapsulation helps in achieving data security, code maintainability, and modularity.

In C#, encapsulation is primarily achieved through the use of access modifiers such as public, private, protected, and internal.

Here's an example that demonstrates encapsulation in C#:

TEXT/X-CSHARP
1public class BankAccount
2{
3    private string accountNumber;
4    private decimal balance;
5
6    public BankAccount(string accountNumber)
7    {
8        this.accountNumber = accountNumber;
9        this.balance = 0;
10    }
11
12    public void Deposit(decimal amount)
13    {
14        balance += amount;
15    }
16
17    public decimal GetBalance()
18    {
19        return balance;
20    }
21}
22
23public class Program
24{
25    static void Main()
26    {
27        BankAccount account = new BankAccount("123456789");
28        account.Deposit(1000);
29        decimal balance = account.GetBalance();
30        Console.WriteLine($"Account balance: {balance}");
31    }
32}

In this example, the BankAccount class encapsulates the account number and balance fields by making them private. Access to these fields is only allowed through the public methods Deposit() and GetBalance(). This ensures that the internal state of the BankAccount object can only be modified or accessed in a controlled manner.

Encapsulation provides several benefits. It helps in preventing unauthorized access to sensitive data, reducing the risk of accidental data corruption. It also allows for better code organization and maintenance. By encapsulating the internal implementation details, the class interface becomes the contract between the class and its users, making it easier to modify the internal implementation without affecting the code that uses the class.

Encapsulation is like a black box. Users of a class only need to know the public methods and properties, while the internal details are hidden. This simplifies the usage of the class, promotes code reusability, and enhances the overall maintainability of the codebase.