Search 
DailyCoding > General

Avoiding Event != null Check

Describes about how we can eliminate the repeating check of Event != null every where in code before raising any event
Author admin on Aug 7, 2008 4 Comments
Rate it    (Rated 3 by 2 people)
1,243 Views

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.

C#

Discussion

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.

Daily Coder On Aug 7, 2008 11:46 AM
Hello Will,
You cannot specify "etc.NewEvent = null;" directly:


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.

Leave a Comment

Name
Email Address
Web Site
© Copyright 2008 Daily Coding • All rights reserved