Created
February 28, 2023 19:01
-
-
Save JerryNixon/705d7f2c0aa8b47741ddb98667058729 to your computer and use it in GitHub Desktop.
Interface, Base, Chained Constructor, Properties, Init, Events, Methods, et al.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IAccount | |
{ | |
int Balance { get; } | |
void Deposit(int amount); | |
void Withdraw(int amount); | |
event EventHandler<int> BalanceChanged; | |
event EventHandler<int> Overdraft; | |
} | |
public abstract class Account : IAccount | |
{ | |
private int balance = 0; | |
public int Balance | |
{ | |
get => balance; | |
private set | |
{ | |
BalanceChanged?.Invoke(this, (balance = value)); | |
if (value < 0) Overdraft?.Invoke(this, value); | |
} | |
} | |
public void Deposit(int amount) => Balance += Math.Abs(amount); | |
public void Withdraw(int amount) => Balance -= Math.Abs(amount); | |
public event EventHandler<int> BalanceChanged; | |
public event EventHandler<int> Overdraft; | |
} | |
public class SavingsAccount : Account | |
{ | |
public SavingsAccount(int number) => AccountNumber = number; | |
public SavingsAccount(int number, string name) | |
: this(number) => AccountName = name; | |
public int AccountNumber { get; } = default; | |
public string AccountName { get; init; } = "No Name Provided"; | |
} | |
var savings = new SavingsAccount(8675309) | |
{ | |
AccountName = "Jerry Nixon", | |
}; | |
savings.BalanceChanged += HandleBalanceChanged; | |
savings.Overdraft += HandleOverdraft; | |
savings.Deposit(100); | |
savings.Deposit(200); | |
savings.Withdraw(300); | |
savings.Withdraw(10); | |
void HandleBalanceChanged(object sender, int balance) | |
{ | |
Console.WriteLine($"New balance is {balance:C0}"); | |
} | |
void HandleOverdraft(object sender, int balance) | |
{ | |
Console.WriteLine($"Invalid balance: {balance:C0}"); | |
} |
Author
JerryNixon
commented
Feb 28, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment