1) Create the event in Customer class. The <TYPE> can be string, decimal, bool, class, etc.
public event EventHandler<decimal> OverdraftEvent;
2) Place code to trigger the event.
public void MakePayment (decimal amount)
{
if (amount < accountFunds) // Not enough. Create event trigger.
OverdraftEvent?.Invoke(this, amount);
}
3) Create listeners for the event. Attached methods to run when event is triggered. You can place the event listeners in different classes/places as needed.
private void WireUpForm()
{
customer.Checking.OverdraftEvent += CheckingAccount_OverdraftEvent;
}
4) Create method that is run when event is triggered.
private void CheckingAccount_OverdraftEvent(object sender, decimal e)
{
// do something to handle event ... for example:
errorMessage.Text = $"Not enough funds available for your {string.Format("{0:C2}", e)} transaction";
}
5) Remove listeners when app is closing. Else, the app may not fully close and get stuck in memory with no garbage collect. This leads to memory leaks !
customer.Checking.OverdraftEvent -= CheckingAccount_OverdraftEvent;
No comments:
Post a Comment