Description
In a recent WPF application I had to map multiple clickable items under one singular list of clickable items. I chose to create a unifying interface for them. The issue was that I wanted to attach event functions to each item and for this I needed to expose the events at the interface layer. It’s like this that I discovered 2 new keywords “add” and “remove“
Solution
The example below is a console application but it explains the procedure.
Let’s start by creating the delegate for our event
public class MoneyTransferedArgs : EventArgs
{
public double ValueTransferred { get; set; }
}
public delegate void MoneyTransferHandler(object sender, MoneyTransferedArgs args);
We now create a base class from which other child classes may inherit. The base class has an event which will be the base event for child classes
public abstract class Bank
{
public event MoneyTransferHandler MoneyTransferred;
public Bank()
{
this.MoneyTransferred += (sender, args) =>
{
Console.WriteLine("Money Transferred : {0}", args.ValueTransferred);
};
}
public virtual void TransferMoney(double amount)
{
this.MoneyTransferred?.Invoke(this, new MoneyTransferedArgs { ValueTransferred = amount });
}
}
Child Implementation
Child classes will be mandated to implement similar events that will only lead to base class event
public interface IBankLocation
{
event MoneyTransferHandler OnMoneyTransferred;
void TransferMoney(double amount);
}
public class BankLocation1 : Bank , IBankLocation
{
public event MoneyTransferHandler OnMoneyTransferred
{
add => this.MoneyTransferred += value;
remove => this.MoneyTransferred -= value;
}
}
public class BankLocation2 : Bank, IBankLocation
{
public event MoneyTransferHandler OnMoneyTransferred
{
add => this.MoneyTransferred += value;
remove => this.MoneyTransferred -= value;
}
}
Result
public abstract class static void Main(string[] args)
{
IBankLocation bankRo1 = new BankLocation1();
IBankLocation bankRo2 = new BankLocation2();
bankRo1.OnMoneyTransferred += (s, e) => Console.WriteLine("Sent With BankRo1");
bankRo2.OnMoneyTransferred += (s, e) => Console.WriteLine("Sent With BankRo2");
bankRo1.TransferMoney(20);
bankRo2.TransferMoney(21);
}










