Yesterday I ran into an interesting (and dangerous) little detail about the C# compiler regarding virtual (field-like) events; they do not behave as you might expect. Consider this code, which I've simplified from a real world example of some refactoring gone wrong:
public abstract class MyClassBase
{
public virtual event EventHandler<EventArgs> MyEvent;
public void DoStuff()
{
if (MyEvent != null)
{
MyEvent(this, EventArgs.Empty);
}
}
}
public class MyClassDerived : MyClassBase
{
public override event EventHandler<EventArgs> MyEvent;
}
To my surprise, when one subscribes to MyEvent, it will never be called:
More...