Cleaner Event Declarations in C#

The traditional event declaration in C# looks something like this:

public event EventHandler Executed;
protected virtual void OnExecuted()
{
    if (this.Executed != null)
        this.Executed(this, EventArgs.Empty);
}

The gratuitous null check in the virtual OnXYZ event caller has always pestered me and I just learned an interesting alternate syntax to avoid this boiler plate code! Behold the cleaner alternative:

public event EventHandler Executed = (o, e) => { };
protected virtual void OnExecuted()
{
    this.Executed(this, EventArgs.Empty);
}

When declaring the event start by assigning it to a lambda, then your event will never be null. Of course there is a minor performance impact to this, but we’re not prematurely optimizing right? Riiiiight?

Author: justinmchase

I'm a Software Developer from Minnesota.

2 thoughts on “Cleaner Event Declarations in C#”

  1. I’ve always hated the event syntax as well, and have been burnt by the standard way of calling them, in your first example. I had to cache the event in a local variable, because another thread was setting it to null in between my null check and calling the method:

    public event EventHandler Executed;
    protected virtual void OnExecuted()
    {
    EventHandler evt = Executed;
    if (evt != null)
    evt(this, EventArgs.Empty);
    }

    Your solution solves this problem, which is nice.

    1. Yeah, I have seen that before as well. If you’re in Wpf/Silverlight you would typically use the Dispatcher to ensure you’re calling/attaching/detaching events so you don’t have to worry about that but we can’t always be so lucky.

Leave a Reply

Discover more from justinmchase

Subscribe now to keep reading and get access to the full archive.

Continue reading