Below is the program I used for the test. It prints (as expected):
Raise A
Event from A
Raise B
Event from B
Now, if we change first two lines of the Main to be:
A a = new B();
B b = new B();
the Program will print:
Raise A
Raise B
Event from B
which is also expected, as overriding event hides the private backing field in the base class and therefore events fired by the base class are not visible to clients of the derived class.
Now I am changing the same lines to:
B b = new B();
A a = b;
and the program starts printing:
Raise A
Raise B
Event from A
Event from B
What's going on?
class A
{
public virtual event EventHandler VirtualEvent;
public void RaiseA()
{
Console.WriteLine("Raise A");
if (VirtualEvent != null)
{
VirtualEvent(this, EventArgs.Empty);
}
}
}
class B : A
{
public override event EventHandler VirtualEvent;
public void RaiseB()
{
Console.WriteLine("Raise B");
if (VirtualEvent != null)
{
VirtualEvent(this, EventArgs.Empty);
}
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
a.VirtualEvent += (s, e) => Console.WriteLine("Event from A");
b.VirtualEvent += (s, e) => Console.WriteLine("Event from B");
a.RaiseA();
b.RaiseB();
}
}