Start learning free

LESSON 64 OF 69 · PROJECTS: OBJECT-ORIENTED

Bank Account in C#: Encapsulation with a Private Balance

Practice Read the full explanation

Build a BankAccount class that keeps its balance private and lets other code change it only through methods that check the rules. This is encapsulation: the object protects its own data.

Private balance. Mark the balance field private double balance, so only the methods of BankAccount can touch it.

What the class must have (C#):

  • public BankAccount(double initialBalance): creates an account that starts with the given balance.
  • public void Deposit(double amount): adds amount to the balance. If amount is zero or negative, do nothing (no error, the balance stays the same).
  • public bool Withdraw(double amount): if amount is zero or negative, or larger than the balance, change nothing and return false. Otherwise subtract it from the balance and return true. Withdrawing exactly the whole balance is allowed (the balance becomes 0).
  • public double GetBalance(): returns the current balance. It is the only way for outside code to read it.

C# method names start with a capital letter: Deposit, Withdraw, GetBalance.

The driver. The driver at the end of the starter code is already written and uses your class. It runs these checks:

class Solution {
    public void MainFunction() {
        BankAccount account = new BankAccount(100);
        account.Deposit(50);
        account.Withdraw(30);
        account.Withdraw(200);
        Console.WriteLine("Balance: " + account.GetBalance());
        account.Deposit(-20);
        account.Deposit(0);
        account.Withdraw(-5);
        Console.WriteLine("Balance: " + account.GetBalance());
        if (account.Withdraw(120)) {
            Console.WriteLine("Withdrew all");
        }
        Console.WriteLine("Balance: " + account.GetBalance());
        if (!account.Withdraw(1)) {
            Console.WriteLine("Rejected");
        }
    }
}

Walk through it: start with 100, deposit 50 (150), withdraw 30 (120), withdraw 200 is refused (still 120). Then deposit -20, deposit 0 and withdraw -5 are all ignored (still 120). Withdrawing 120 succeeds and empties the account, so the balance is 0, and withdrawing 1 more is refused.

Expected output:

Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected

Both deposit and withdraw start with a guard that rejects amount <= 0. Write the guard first, then the change to the balance.

private double balance;, then in the constructor balance = initialBalance;.

if (amount <= 0 || amount > balance) return false;, then balance -= amount; and return true;.

class BankAccount {
    private double balance;

    public BankAccount(double initialBalance) {
        balance = initialBalance;
    }

    public void Deposit(double amount) {
        if (amount <= 0) return;
        balance += amount;
    }

    public bool Withdraw(double amount) {
        if (amount <= 0 || amount > balance) return false;
        balance -= amount;
        return true;
    }

    public double GetBalance() {
        return balance;
    }
}

class Solution {
    public void MainFunction() {
        BankAccount account = new BankAccount(100);
        account.Deposit(50);
        account.Withdraw(30);
        account.Withdraw(200);
        Console.WriteLine("Balance: " + account.GetBalance());
        account.Deposit(-20);
        account.Deposit(0);
        account.Withdraw(-5);
        Console.WriteLine("Balance: " + account.GetBalance());
        if (account.Withdraw(120)) {
            Console.WriteLine("Withdrew all");
        }
        Console.WriteLine("Balance: " + account.GetBalance());
        if (!account.Withdraw(1)) {
            Console.WriteLine("Rejected");
        }
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    C# · PROJECTS: OBJECT-ORIENTED

    Bank Account in C#, explained

    Problem overview

    You build a BankAccount class whose balance can't be changed from outside. The balance is a private double field, so only the class's own methods can touch it. Everything else goes through four members:

    • BankAccount(double initialBalance) creates an account with a starting balance.
    • Deposit(double amount) adds money, and does nothing when the amount is zero or negative.
    • Withdraw(double amount) returns false and changes nothing when the amount is zero, negative or more than the balance. Otherwise it subtracts the amount and returns true.
    • GetBalance() returns the balance. It is the only way to read it from outside.

    The program already in the editor starts an account at 100, deposits 50 and withdraws 30, which leaves 120. A withdrawal of 200 is refused, so the balance is still 120. The deposits of -20 and 0 and the withdrawal of -5 are ignored. Then Withdraw(120) succeeds and empties the account, and Withdraw(1) is refused.

    Approach: guard first, then change

    Think of the class as a small contract. Callers may ask for a deposit or a withdrawal, and they learn the result through the return value or GetBalance(). They can never reach in and set the number themselves.

    This is encapsulation: the object protects its own data. If balance were public, any code could write account.balance = -1000. With a private field, the only way in is through Deposit and Withdraw, and each of them checks the rules before it changes anything.

    Both methods follow the same pattern. They start with a guard that rejects bad input and leaves right away. Code after the guard can assume the input is valid, so the real work is one line.

    Step by step

    1. Declare the class BankAccount. Everything about an account lives inside it.
    2. Add the field private double balance;. It is the account's hidden state.
    3. Write the constructor. It is public, has the class's name and no return type, and takes initialBalance. It runs once when the driver says new BankAccount(100).
    4. Store the starting value in balance. The parameter and the field have different names, so no this. is needed.
    5. Write Deposit as a public void method. A deposit gives no answer back, so it returns nothing.
    6. Guard it: if (amount <= 0) return;. A deposit of zero or less leaves the method before anything changes.
    7. Add the amount to balance. Only a positive amount gets here.
    8. Write Withdraw as a public method returning bool, so the caller learns whether the money left.
    9. Guard it with two reasons to refuse: the amount is not positive, or it is larger than the balance. Both return false. Asking for exactly the whole balance passes the guard, because amount > balance is false then.
    10. Subtract the amount from balance.
    11. Return true. Reaching this line means the withdrawal happened.
    12. Write GetBalance as a public method returning double with no parameters.
    13. Return balance. The caller gets a copy of the number and still can't change the field.

    The solution in C#

    class BankAccount {
        private double balance;
    
        public BankAccount(double initialBalance) {
            balance = initialBalance;
        }
    
        public void Deposit(double amount) {
            if (amount <= 0) return;
            balance += amount;
        }
    
        public bool Withdraw(double amount) {
            if (amount <= 0 || amount > balance) return false;
            balance -= amount;
            return true;
        }
    
        public double GetBalance() {
            return balance;
        }
    }
    
    class Solution {
        public void MainFunction() {
            BankAccount account = new BankAccount(100);
            account.Deposit(50);
            account.Withdraw(30);
            account.Withdraw(200);
            Console.WriteLine("Balance: " + account.GetBalance());
            account.Deposit(-20);
            account.Deposit(0);
            account.Withdraw(-5);
            Console.WriteLine("Balance: " + account.GetBalance());
            if (account.Withdraw(120)) {
                Console.WriteLine("Withdrew all");
            }
            Console.WriteLine("Balance: " + account.GetBalance());
            if (!account.Withdraw(1)) {
                Console.WriteLine("Rejected");
            }
        }
    }
    

    The driver prints:

    Balance: 120
    Balance: 120
    Withdrew all
    Balance: 0
    Rejected
    

    C# details

    • private is checked by the compiler. Writing account.balance = 1000 outside the class is a compile error: 'BankAccount.balance' is inaccessible due to its protection level. Rule-breaking code never gets to run.
    • Methods can see private fields of the same class. That is why Deposit may write balance while a caller may not. Any other BankAccount object's private fields are visible inside the class too, but this lesson never needs that.
    • Method names start with a capital letter in C#: Deposit, Withdraw, GetBalance.
    • Console.WriteLine("Balance: " + account.GetBalance()) joins text and a double. A double holding 120 prints as 120, not 120.0.
    • A one-line if with return and no braces is valid, and the guard is short enough to read that way.

    Edge cases and common mistakes

    • Guard after the change. If Deposit added the amount and then checked it, a negative deposit would already have lowered the balance. Check first.
    • Using >= in the withdraw guard. That would refuse the exact balance, so Withdraw(120) would fail and the account could never be emptied.
    • Forgetting the <= 0 part in Withdraw. Withdraw(-5) would then pass and raise the balance by 5.
    • Fractions. A double stores binary approximations. Depositing 0.1 and then 0.2 into an empty account gives a balance of 0.30000000000000004, so Withdraw(0.3) returns true and leaves about 5.55E-17 behind instead of 0. The lesson uses whole numbers, but this is why real money code often uses decimal.
    • Just over the balance. On an account with 100, Withdraw(100.01) returns false and the balance stays 100.

    Why Withdraw returns a bool

    Deposit silently ignores a bad amount, but Withdraw reports success or failure. The difference matters because a refused withdrawal is something the caller usually has to react to: in the driver, if (account.Withdraw(120)) prints Withdrew all only when the money really left, and if (!account.Withdraw(1)) prints Rejected. A void method could not tell the caller which happened. The earlier calls in the driver, such as account.Withdraw(200);, ignore the result, and C# allows that.

    Testing

    • A new account with 10.5: Withdraw(10.5) returns True and GetBalance() then gives 0.
    • An account with 100: Withdraw(100.01) returns False and GetBalance() still gives 100.
    • After the driver ends, one more Withdraw(1) on the empty account returns False.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free