Skip to content
Tutorials Center
My learning

Topics

Lesson 171 of 182 ยท Projects

Project: Bank Account System

Build a bank in C# in four stages: decimal money and custom exceptions, account classes and events, atomic transfers behind one lock, and an audit log you can replay to prove the books balance.

Money is the classic example for object-oriented design, because the rules are strict and mistakes are visible. A balance must never be wrong. A withdrawal that would break the rules must be refused with a clear reason. A transfer must either happen completely or not at all, and no cent may appear from nowhere. If you can build a bank that keeps those promises, you understand the everyday core of C#: decimal, inheritance and interfaces, exceptions you design yourself, events, and keeping shared state safe.

You build the bank in four stages, and each stage is a complete program. In stage 1 you model accounts with an abstract base class, subclasses, decimal arithmetic and custom exceptions. In stage 2 you add Transaction records, an event that fires whenever money moves, and an audit log that listens to it. In stage 3 you add a Bank that opens accounts and makes transfers atomic behind a single lock. In stage 4 you add monthly interest and fees, statements, and a verifier that replays the audit log to prove that the books balance, even after two thousand concurrent transfers.

This is a teaching model. A real bank also needs authentication, durable storage with database transactions, idempotency keys and regulators. What you learn here (money as decimal, invariants, atomic multi-step operations, an append-only audit trail) carries over to all of that.

The plan

Stage New idea Tools
1 Accounts and rules decimal, abstract classes, custom exceptions
2 Observing changes events, records, enums
3 Atomic transfers lock, dictionaries, internal members
4 Proof and reports LINQ, Parallel.For, string formatting

Stage 1: accounts, decimal and exceptions

Money is decimal

Never store money in double. A double is a binary fraction, and most decimal fractions such as 0.1 have no exact binary form, so errors creep in. The decimal type stores base-10 digits exactly (28-29 significant digits), which is what money needs.

The accounts below also refuse nonsense. An amount must be positive and have at most two decimal places; 10.005 is rejected rather than rounded silently, because silently rounding a customer's money is how arguments start. Rules like these belong in one place (Money.Check), not scattered through every method.

Accounts are a small class hierarchy. The abstract base class holds the shared behaviour (balance, deposit, withdraw) and asks each subclass one question: how far below zero may this account go?

  • A CheckingAccount has an agreed overdraft limit (zero by default).
  • A SavingsAccount may never go below zero.

The failures are exception types you design yourself. Each carries the facts a caller needs (the shortfall, not just a message string), and they all derive from BankException, so a caller can catch "anything the bank refuses" in one catch.

C# Stage 1: Account, CheckingAccount, SavingsAccount, exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look at the design choices:

  • ten times 0.1. The double total is not exactly 1.0, the decimal total is. Run it and see the real digits that :R prints for the double.
  • The template method. Withdraw is written once in the base class, and the one thing that differs between account types, OverdraftLimit, is a protected abstract property (abstract classes). Adding a StudentAccount later means writing one small class, not copying Withdraw.
  • A private setter protects the balance. Only Account itself can change Balance, so every change goes through code that checks the rules. This is encapsulation doing real work (properties).
  • Check before you change. Withdraw validates everything first and mutates last. If any check throws, the balance is untouched. This "validate, then mutate" order is the basis of the transfer logic in stage 3.
  • Exceptions carry data. InsufficientFundsException.Shortfall lets a UI say "you need 50.00 more" without parsing a message. Catch the specific exception first and the general BankException last, or the specific catch could never run (custom exceptions).
  • Primary constructors keep each class to its essentials. The base-class constructor arguments are passed straight through in the header (: Account(id, owner)) (primary constructors).

A decimal constant needs the m suffix: 0.1m. Without it, 0.1 is a double literal, and mixing double and decimal in one expression does not compile. That is a feature: the compiler stops you from sneaking binary floating point into money code.

Stage 2: transactions and events

A bank must be able to answer "what happened to this account?". The balance alone cannot, since it is only the sum of the past. So every change creates a Transaction: an immutable record with the account, the kind of movement, the amount, the resulting balance and a note. An enum names the kinds.

How should that record reach the audit log? The account could call auditLog.Add(...) directly, but then every account needs to know about the log, and adding a second listener (an alert for big withdrawals, say) means editing the account again. The account should not care who is listening. That is the job of an event: the account announces "I posted a transaction" and any number of subscribers react.

C#
public event EventHandler<Transaction>? Posted;

EventHandler<T> is the standard delegate for events: it passes the sender and the data. The ? is there because an event with no subscribers is null, and Posted?.Invoke(this, tx) raises it only when someone listens (events). Subscribers use += and -=; they cannot raise the event or replace the other subscribers, which a plain delegate field would allow.

C# Stage 2: a Posted event and an audit log

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notes on the event design:

  • State first, announcement second. Post sets Balance and then raises Posted. A subscriber that reads account.Balance inside the handler sees the new, consistent value. Always raise an event after your own state is valid.
  • Handlers run synchronously, in subscription order, on the caller's thread, before Deposit returns. That is convenient (the log is up to date the moment the call returns) and dangerous: if a handler throws, the exception comes out of Deposit, even though the money has already moved, and the handlers after it are skipped. Audit handlers must therefore be tiny and must not throw. For slow work, a handler should put the transaction in a queue and return (channels).
  • Unsubscribe when you are done. The account holds a reference to every subscriber, so a short-lived listener that is never removed (-=) keeps itself alive as long as the account lives: a classic memory leak. A lambda cannot be unsubscribed unless you keep it in a variable, which is why the method group log.Record is used for the subscription we later remove.
  • The record's ToString uses alignment ({Amount,10:N2}) so entries line up like a statement (output formatting).
  • IReadOnlyList hides the list. Entries exposes the log for reading but not for editing. An audit log that anyone can edit is not an audit log. (A determined caller could cast it back to List; for real protection return a copy or an ImmutableArray, see immutable collections.)

Stage 3: a Bank, and transfers that cannot half-happen

Now several accounts must work together. A transfer is the interesting part: it withdraws from one account and deposits into another, and the bank must never end in the middle. Imagine the withdrawal succeeds and the deposit then fails because the destination account is frozen. The money has vanished.

There are two ways to prevent that:

  1. Compensation: do step 1, try step 2, and if it fails, undo step 1. This works with external systems you cannot lock (a payment provider), but the undo can fail too, and the audit log fills with the withdrawal and the reversal.
  2. Validate everything, then apply. Check that both sides will succeed, then perform both changes. When the bank owns all the data and holds a lock, the second phase cannot fail, so there is nothing to undo.

We use the second approach. It needs two things. The account gets CheckDebit and CheckCredit methods that throw if the movement would be refused (and change nothing), and one lock in the Bank so no other thread can change either account between the check and the action.

The account's mutating methods become internal, so callers must go through the Bank. (In a real solution the bank and accounts live in one project and the outside world in another, which makes internal a hard wall. In one file it documents the intent.) The bank also opens accounts with generated ids, subscribes the audit log to each new account, and can freeze an account to demonstrate a refusal.

C# Stage 3: Bank, atomic transfers and a frozen account

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

How the pieces fit together:

  • Check, then act, under one lock. Transfer calls CheckDebit and CheckCredit before touching anything. Look at the output for the transfer to the frozen account: it is refused, and the audit log has no half-finished entry. The lock is what makes "cannot fail now" true; without it another thread could drain the source account between the check and the debit.
  • System.Threading.Lock (new in .NET 9 / C# 13) is the modern lock object. lock (_gate) on a Lock uses its efficient scope API. Do not lock on this, on a string, or on a typeof(...): someone else can lock on the same object and cause surprising stalls (synchronization).
  • A single coarse lock is a deliberate choice. It makes the reasoning trivial (only one operation at a time), and a coarse lock is plenty fast for thousands of operations per second because each holds it for microseconds. Per-account locks give more parallelism but need a fixed locking order to avoid deadlock (always lock the lower id first), and you only want that complexity when a measurement says the single lock is a bottleneck.
  • Validation order in CheckDebit. Amount first, then frozen, then funds. The order decides which message the customer sees when two things are wrong, so decide it on purpose.
  • Generated ids. $"ACC-{_nextNumber++:D4}" produces ACC-0001, ACC-0002, and so on. SortedDictionary with an ordinal comparer keeps accounts in id order, so every listing is deterministic. A plain Dictionary with string keys has no promised order.
  • Func<string, Account> as a factory. Open does the shared work (new id, subscribe the log, store) and lets the caller decide only which kind of account to build. The two public Open... methods are one-liners.
  • The audit log is attached by the bank, not by whoever creates an account, so no account can ever exist without being audited. Design so that the safe thing happens by default.

When a method has to change two things "together", ask whether the second step can fail. If it can, either check first (as here) or plan an undo. If you write step 2 and think "this should never fail", turn that thought into a check, and make the lock cover it.

Stage 4: interest, fees, statements and proof

A bank that cannot show its work is not trusted. The last stage adds month-end processing and a way to check the books.

Month-end processing adds interest to savings accounts and charges a fee on checking accounts that are below a minimum balance. Interest is a classic rounding problem: balance * rate / 12 usually has more than two decimal places. We round with MidpointRounding.ToEven ("banker's rounding"): halves go to the nearest even digit, so rounding errors do not all lean the same way over millions of accounts. (Math.Round uses this by default; it is not the "round half up" you learned at school, which is MidpointRounding.AwayFromZero.)

Verification is the idea to remember from this project. Every balance is supposed to equal the sum of the signed transactions in the audit log. So a checker can replay the log and compare, and it can check each entry's BalanceAfter against the running total. Any bug that changes a balance without logging it, or logs something different from what it did, shows up as a mismatch. We keep the replay logic in a pure static method that takes the entries and the balances, so we can also feed it a deliberately damaged log and watch it complain.

Finally a stress test: two thousand transfers between four accounts on many threads at once with Parallel.For. The exact interleaving differs on every run, and so does the final split of money between the accounts, so we do not print it. What must be the same every time are the invariants: the total amount of money is unchanged (transfers only move it), and the replay finds no problems. Testing an invariant instead of an exact output is the standard way to test concurrent code.

C# Stage 4: month end, statements and a replay verifier

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

What this stage demonstrates:

  • Rounding is a business rule. Banker's rounding sends 2.345 to 2.34 (the neighbour with an even last digit) and 2.355 to 2.36; "away from zero" sends both up. Which one is correct depends on the contract, so name the mode explicitly in code instead of relying on defaults.
  • A switch statement with type patterns and a when guard picks the right month-end rule per account type, with no if (account is ...) chain and no virtual method that every account class must implement (pattern matching). If the rules grew, a method on each account class would scale better; for two rules a switch keeps them all in one readable place.
  • The replay verifier is independent. It does not call any code that moved money. It only reads the log and the balances. Verification code that shares its logic with the code it checks proves much less.
  • The damaged log is caught. We drop Cy's opening deposit from the copy. The replayed running total then disagrees with the next entry's BalanceAfter, and the message names the account and the first entry where the chain breaks. The verifier resynchronises after reporting, so one missing entry gives one report instead of a flood.
  • Invariants for concurrency. The stress test prints only facts that hold on every run. The final balances of the four accounts differ from run to run, so printing them would make the test flaky; "total unchanged" and "no replay problems" never do. The refused counter uses Interlocked.Increment because many threads update it at once (threads).
  • new Random(i) per iteration makes each transfer's inputs a pure function of i, so the set of transfers is the same every run even though their order is not.
  • Where the lock is held. The log's List is not thread safe, and it is safe here only because every Post happens while the bank's lock is held. If you ever call an account's Credit outside the bank, you break that guarantee. This is why those methods are internal.

Extending the bank

Each of these makes you use a different tool, and the design above leaves room for all of them:

  1. Frozen accounts at month end. EndOfMonth skips them. Write the test that proves it.
  2. A daily withdrawal limit. Keep per-day totals in CheckingAccount. Inject a TimeProvider as in the to-do project so the test controls the date.
  3. Per-account locks. Replace the single lock with one Lock per account and lock the lower id first. Run the stress test with more threads and compare the throughput. Does it help?
  4. Persist the audit log as JSON lines, rebuild the whole bank by replaying them at start-up (event sourcing in miniature), and use Ledger.Verify to detect a corrupted file.
  5. An IAccountRule interface (MinimumBalanceRule, DailyLimitRule) that CheckDebit consults, so policies become plug-ins (interfaces).
  6. Expose the bank over HTTP with a minimal API, then turn the exceptions into proper problem responses (validation and problem details).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should money be stored as decimal rather than double?

    A double is a binary fraction and cannot hold 0.1 exactly, so sums drift. decimal stores base-10 digits, which matches how money is written. It does not round automatically and is larger and slower than double.
  2. 2. In Transfer, what makes it safe to say the second phase cannot fail?

    CheckDebit and CheckCredit run first and throw before anything changes. Because the whole method holds one lock, no other thread can alter either balance between the check and the action.
  3. 3. What is a risk of handlers subscribed to an account's Posted event?

    Events invoke handlers synchronously on the caller's thread. An exception in a handler propagates to the code that raised the event and skips later handlers, so audit handlers must be small and must not throw.
  4. 4. Why does the stress test print only the total amount of money and the number of replay problems, not the final balances?

    With concurrent transfers the order differs between runs, so the final split changes. Testing invariants, which must hold for every interleaving, gives a reliable test.
  5. 5. What does Math.Round(2.345m, 2, MidpointRounding.ToEven) return?

    ToEven (banker's rounding) sends an exact half to the neighbour whose last digit is even: 2.345 becomes 2.34. MidpointRounding.AwayFromZero would give 2.35.

Summary

  • Store money in decimal, validate amounts in one helper, and reject values with too many decimal places instead of rounding them silently.
  • Put shared behaviour in an abstract base class and let subclasses answer small questions (here, the overdraft limit); design exceptions that carry data and share a common base type.
  • Use an event to announce changes without the account knowing its listeners; raise it after your state is valid, keep handlers tiny, and unsubscribe when you are done.
  • Make multi-step operations atomic by validating everything first and applying everything second under one lock; hide the unsafe mutators behind internal.
  • Round on purpose: choose the MidpointRounding mode that the business rule requires.
  • An append-only audit log plus an independent replay verifier proves the state; test concurrent code with invariants, not exact outputs.

Next: Project: Inventory REST API