C# Encapsulation


Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP) in C#. It refers to the bundling of data (attributes) and methods (functions) 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 help prevent unintended interference and misuse of the methods and data. This is typically achieved through access modifiers.

Key Concepts of Encapsulation

  1. Access Modifiers: These define the visibility of class members (fields, properties, and methods). Common access modifiers include:

    • public: Accessible from anywhere.
    • private: Accessible only within the same class.
    • protected: Accessible within the same class and by derived class instances.
    • internal: Accessible within the same assembly.
    • protected internal: Accessible within the same assembly and by derived classes.
  2. Properties: These are special methods called "accessors" that provide a flexible mechanism to read, write, or compute the values of private fields.

  3. Methods: These are functions defined in a class that can manipulate the data of the class.

Example of Encapsulation

Let's create a simple class to demonstrate encapsulation using a BankAccount class.

csharp
1using System; 2 3public class BankAccount 4{ 5 // Private fields 6 private string accountNumber; 7 private decimal balance; 8 9 // Constructor to initialize the account 10 public BankAccount(string accountNumber, decimal initialBalance) 11 { 12 this.accountNumber = accountNumber; 13 this.balance = initialBalance; 14 } 15 16 // Public property to get the account number 17 public string AccountNumber 18 { 19 get { return accountNumber; } 20 } 21 22 // Public property to get the balance 23 public decimal Balance 24 { 25 get { return balance; } 26 } 27 28 // Method to deposit money 29 public void Deposit(decimal amount) 30 { 31 if (amount > 0) 32 { 33 balance += amount; 34 Console.WriteLine($"Deposited: {amount}. New balance: {balance}"); 35 } 36 else 37 { 38 Console.WriteLine("Deposit amount must be positive."); 39 } 40 } 41 42 // Method to withdraw money 43 public void Withdraw(decimal amount) 44 { 45 if (amount > 0 && amount <= balance) 46 { 47 balance -= amount; 48 Console.WriteLine($"Withdrew: {amount}. New balance: {balance}"); 49 } 50 else 51 { 52 Console.WriteLine("Invalid withdrawal amount."); 53 } 54 } 55} 56 57public class Program 58{ 59 public static void Main() 60 { 61 // Create a new bank account 62 BankAccount account = new BankAccount("123456789", 1000m); 63 64 // Display account number and balance 65 Console.WriteLine($"Account Number: {account.AccountNumber}"); 66 Console.WriteLine($"Initial Balance: {account.Balance}"); 67 68 // Deposit money 69 account.Deposit(500m); 70 71 // Withdraw money 72 account.Withdraw(200m); 73 74 // Attempt to withdraw more than the balance 75 account.Withdraw(2000m); 76 77 // Display final balance 78 Console.WriteLine($"Final Balance: {account.Balance}"); 79 } 80}

Explanation of the Example

  1. Private Fields: The accountNumber and balance fields are declared as private, meaning they cannot be accessed directly from outside the BankAccount class. This protects the integrity of the data.

  2. Public Properties: The AccountNumber and Balance properties provide read-only access to the private fields. The get accessor allows external code to retrieve the values without allowing direct modification.

  3. Methods: The Deposit and Withdraw methods provide controlled access to modify the balance. They include validation to ensure that:

    • The deposit amount is positive.
    • The withdrawal amount is valid (greater than zero and less than or equal to the balance).

Benefits of Encapsulation

  • Data Protection: By restricting access to the internal state of the object, encapsulation helps prevent accidental changes or misuse of the data.
  • Controlled Access: Through methods and properties, you can define how the data can be accessed or modified, allowing for validation and other logic to be applied.
  • Maintainability: Changes to the internal implementation of a class can be made without affecting the code that uses the class, as long as the public interface remains the same.
  • Improved Code Readability: Encapsulation helps in organizing code better, making it easier to understand and manage.

Talk to us?

Post your blog