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)returnsfalseand changes nothing when the amount is zero, negative or more than the balance. Otherwise it subtracts the amount and returnstrue.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
- Declare the class
BankAccount. Everything about an account lives inside it. - Add the field
private double balance;. It is the account's hidden state. - Write the constructor. It is public, has the class's name and no return type, and takes
initialBalance. It runs once when the driver saysnew BankAccount(100). - Store the starting value in
balance. The parameter and the field have different names, so nothis.is needed. - Write
Depositas a publicvoidmethod. A deposit gives no answer back, so it returns nothing. - Guard it:
if (amount <= 0) return;. A deposit of zero or less leaves the method before anything changes. - Add the amount to
balance. Only a positive amount gets here. - Write
Withdrawas a public method returningbool, so the caller learns whether the money left. - 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, becauseamount > balanceis false then. - Subtract the amount from
balance. - Return
true. Reaching this line means the withdrawal happened. - Write
GetBalanceas a public method returningdoublewith no parameters. - 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
privateis checked by the compiler. Writingaccount.balance = 1000outside 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
Depositmay writebalancewhile a caller may not. Any otherBankAccountobject'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 adouble. Adoubleholding 120 prints as120, not120.0.- A one-line
ifwithreturnand no braces is valid, and the guard is short enough to read that way.
Edge cases and common mistakes
- Guard after the change. If
Depositadded 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, soWithdraw(120)would fail and the account could never be emptied. - Forgetting the
<= 0part inWithdraw.Withdraw(-5)would then pass and raise the balance by 5. - Fractions. A
doublestores binary approximations. Depositing 0.1 and then 0.2 into an empty account gives a balance of0.30000000000000004, soWithdraw(0.3)returnstrueand leaves about 5.55E-17 behind instead of 0. The lesson uses whole numbers, but this is why real money code often usesdecimal. - Just over the balance. On an account with 100,
Withdraw(100.01)returnsfalseand 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)returnsTrueandGetBalance()then gives0. - An account with 100:
Withdraw(100.01)returnsFalseandGetBalance()still gives100. - After the driver ends, one more
Withdraw(1)on the empty account returnsFalse.
