Mid From PDF OOP C# OOP

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)
{
ccountNumber = accNum;

balance = initialBalance >= 0 ? initialBalance : throw new

rgumentException("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.

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details