Avoiding Event != null Check

Lets take a simple example of declaring and raising a custom event. Look at the code below:

public class EventTestClass
{
    public event EventHandler NewEvent;

    protected void OnNewEvent()
    {
        NewEvent(this, EventArgs.Empty);
        // Above code will raise System.NullReferenceException
        // exception if there is no handler registered with it.
    }
}

As you know if if don't attach any handler to the NewEvent above then the OnNewEvent will throw exception because the NewEvent is null at that time. To get rid of this we generally put a null check on the event as shown below:

public class EventTestClass
{
    public event EventHandler NewEvent;

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

There could be better way solving problem look at the solution below:

public class EventTestClass
{
    public event EventHandler NewEvent = delegate { };

    protected void OnNewEvent()
    {
        NewEvent(this, EventArgs.Empty);
    }
}

The above code will work perfectly fine even if you don't attach any handler to the event. This is because the event is not null now as we have already registered on empty handler with it.

10 comment(S)


Will on Aug 7, 2008 11:37 AM

Do me a fav; run the following and report back what happens:

EventTestClass etc = new EventTestClass();
etc.NewEvent = null;
etc.FireEventLol();

where FireEventLol is:

public void FireEventLol() { OnNewEvent(); }

Will on Aug 7, 2008 11:39 AM

Wait, strike that... I'll put my dumbass hat back on.

Anonymous on Aug 8, 2008 02:26 AM

This is indeed a nice idea, just a note to consider when using this approach -- there might be a small performance difference when custom event args are initialized inside the calling method, for example the following block of code:

public event EventHandler<CustomEventArgs> NewEvent = delegate { };
(...)
// without checking if (NewEvent != null)
NewEvent(this, new CustomEventArgs(someDataToPass));

will create a new instance of CustomEventArgs every time even if NewEvent does not contain any handlers. I usually prefer to create this instance just after the null check - this should of course only be considered if there is a big number of potentially uninitialized custom event handlers and the expected firing rate is relatively high.

Visual C# Kicks on Jan 12, 2009 02:44 PM

That's pretty catchy. Does it cause any memory issues?

Lexy on Jul 23, 2009 07:04 AM

"That's pretty catchy. Does it cause any memory issues?"
I think not because you just notify an "empty" delegate.

Generally I only see disadvantiges in this method. An event itself in .NET is a pricy thing, so only use this method for events that fire very very rarely.

"There could be better way solving problem look at the solution below:"
Whats better in this solution?

Greetings

Just a dude on Aug 14, 2009 10:38 PM

"Whats better in this solution?"

No, one has mentioned here the main reason the "event != null" pattern is avoided. The problem? Race condition!

In a multi-threaded environment these checks seem innocuous but are dangerous. Without putting in an empty delegate you'd have to implement a mutex to perform the check and call in which in my completely non-scientifically proven opinion is more expensive then notifying an empty delegate.

Nick on Sep 10, 2009 01:31 PM

If your removing and adding multicast events on multiple threads. It's not the race condition you need to worry about. It's how quickly you can fire the developer!


Jason on Nov 3, 2011 07:45 PM

There is one problem with this if your delegate has out parameters.

Another dude on Jul 20, 2012 08:59 AM

Just what I was looking for. I hates if statements...

Leave a comment