Pattern for dealing with null handler for events in C#

If you’ve used events in C# before, you’ve prob­a­bly writ­ten code like this too:

public event EventHandler Started;
// make sure Started is not null before firing the event
// else, NullReferenceException will be thrown
if (Started != null)
    Started(this, some_event_args);

This is per­fect­ly ok and nor­mal to do, but can quick­ly become tire­some if you have to fire events in mul­ti­ple places in your code and have to do a null ref­er­ence check every time!

So instead, I have been using this pat­tern for a while:

// initialise with empty event hanlder so there's no need for Null reference check later
public event EventHandler Started = (s, e) => { };
// no need for Null reference check anymore as Started is never null
Started(this, some_event_args);

If all you need is the abil­i­ty to add/remove han­dlers, then this pat­tern would do you fine as the event will nev­er be null because there’s no way for you to remove the anony­mous method the event was ini­tialised with unless you set the event to null.

How­ev­er, if you occa­sion­al­ly need to clear ALL the event han­dlers and set the event to null, then don’t use this pat­tern as you might start see­ing Null­Ref­er­ence­Ex­cep­tion being thrown before you add event han­dlers back in.

Liked this post? Why not support me on Patreon and help me get rid of the ads!