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­fectly ok and nor­mal to do, but can quickly 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­ity to add/remove han­dlers, then this pat­tern would do you fine as the event will never 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­ever, if you occa­sion­ally 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.

Share

Leave a Reply