C Sharp (C#) - Classes and Objects
You want to create a class
BankAccount that remembers the balance for each account. Which design correctly uses instance fields to track the balance and safely update it?class BankAccount {
private decimal balance;
public BankAccount(decimal initial) {
balance = initial;
}
public void Deposit(decimal amount) {
if (amount > 0) {
balance += amount;
}
}
public bool Withdraw(decimal amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
}
return false;
}
public decimal GetBalance() {
return balance;
}
}