Encapsulated Bank Account
This exercise applies encapsulation instead of exposing writable state.
How it works
Protect a balance with validated domain methods.
A private setter prevents arbitrary changes while Deposit enforces the account rule.
Runnable C# example
Program.cs
using System;
class BankAccount(decimal opening)
{
public decimal Balance { get; private set; } = opening;
public void Deposit(decimal amount)
{
if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
Balance += amount;
}
}
class Program
{
static void Main() { var account = new BankAccount(100); account.Deposit(50); Console.WriteLine(account.Balance); }
}
150Practice with the debugger
Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.