I have a SelectionChanged event in class A that I want to relay through class B. I assumed that declaring a SelectionChanged event in class B and assigning this EventHandler to A.SelectionChanged would cause B.SelectionChanged to trigger whenever A.SelectionChanged was triggered – this turned out to be false.
To be more clear, some code:
class A
{
public event EventHandler SelectionChanged;
public void TriggerSelectionChanged()
{
if (SelectionChanged != null) SelectionChanged(this, EventArgs.Empty);
}
}
class B
{
private A _a = new A();
public A A { get { return _a; } }
public event EventHandler SelectionChanged;
public B()
{
A.SelectionChanged += SelectionChanged;
}
public static void Test()
{
B relayer = new B();
bool wasRelayed = false;
relayer.SelectionChanged += delegate { wasRelayed = true; };
relayer.A.TriggerSelectionChanged();
System.Console.WriteLine("Relayed: {0}", wasRelayed);
}
}
This prints out “Relayed: false”.
What are the effects of adding an EventHandler to another EventHandler?
EDIT:
Note! I’m aware of that a solution to this is to relay the event through an delegate, function etc etc, but I’m mostly interrested in knowning what the effects of this code is.
It turns out that this is an effect from EventHandler being a Delegate. This class implements operator += through (or so I assume) using Delegate.Combine. The documentation of this function reads
What happens is that all handlers assigned to the EventHandler on the right side are added to the EventHandler on the left. In this case there’s zero handlers so nothing happens. However, if the order of things are changed such that
B.SelectionChangedis assigned beforeB.SelectionChangedis connected toA.SelectionChangedthings are hooked up correctly. However, removing an handler from B does not remove it from A so doing this should be highly frawned upon.