Skipping Null Checks on Events

Yesterday I learned a neat C# trick that can be used to skip the traditional null check associated with defining, then firing events:

public class MyClassWithAnEvent
{
    public event EventHandler MyEvent;

    protected void FireMyEvent()
    {
        if (MyEvent != null)
            MyEvent(this, EventArgs.Empty);
    }
}

By immediately assigning the event with an empty event handler, we can guarantee that the event is never null, thereby saving us a line of code whenever we call it:

public class MyClassWithAnEvent
{
    public event EventHandler MyEvent = (o, e) => {};

    protected void FireMyEvent()
    {
        MyEvent(this, EventArgs.Empty);
    }
}

Posted on October 20, 2010 from Calgary

About

My name is Brandur. I'm a polyglot software engineer and part-time designer working at Heroku in San Francisco, California. I'm a Canadian expat. My name is Icelandic. Drop me a line at brandur@mutelight.org.

Aside from technology, I'm interested in energy and how it relates to our society, travel, longboarding, muay thai, symphonic metal, and the guitar.

If you liked this article, consider finding me on Twitter.