Skip to content

Instantly share code, notes, and snippets.

@JerryNixon
Created February 28, 2023 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JerryNixon/705d7f2c0aa8b47741ddb98667058729 to your computer and use it in GitHub Desktop.
Save JerryNixon/705d7f2c0aa8b47741ddb98667058729 to your computer and use it in GitHub Desktop.
Interface, Base, Chained Constructor, Properties, Init, Events, Methods, et al.
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}");
}
@JerryNixon
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment