Give an example of encapsulation in C#.?
Real-World Example: Bank Account Management
public class BankAccount
private string accountNumber; // private field
private decimal balance; // private field
public string AccountNumber { get { return accountNumber; } } //
read-only
public decimal Balance { get { return balance; } } //
read-only
public BankAccount(string accNum, decimal initialBalance)
accountNumber = accNum;
balance = initialBalance >= 0 ? initialBalance : throw new
ArgumentException("Invalid balance");
public void Deposit(decimal amount)
if(amount > 0) balance += amount;
else throw new ArgumentException("Deposit must be
positive");
public void Withdraw(decimal amount)
if(amount > 0 && amount <= balance) balance -= amount;
else throw new InvalidOperationException("Insufficient
balance");
// Usage
BankAccount myAccount = new BankAccount("ACC123", 1000);
myAccount.Deposit(500); // Balance becomes 1500
myAccount.Withdraw(200); // Balance becomes 1300
Console.WriteLine($"Account: {myAccount.AccountNumber}, Balance:
{myAccount.Balance}");
Explanation:
- accountNumber and balance are private, protecting sensitive data.
- Controlled access via methods ensures data integrity.
- Demonstrates real-world encapsulation in action.
🔹 Section 3: Abstraction – Interview Q&A