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.