Virtual events in C#

by Marcel Veldhuizen 11. June 2014 08:06

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...

Tags: , , ,

Programming | .NET

Marcel Veldhuizen

Software Architect by profession, mostly focused on Microsoft .NET technology.

Metal enthusiast; I love going to concerts :)

 

RecentPosts

Recent Tweets

Note: For Customization and Configuration, CheckOut Recent Tweets Documentation