DCSIMG
A Handy Extension Method: Raise Events Safely - IronShay

A Handy Extension Method: Raise Events Safely

Raising events is a very common practice. We do that a lot and it’s pretty irritating to check for nullity every time:

if (eventHandler != null)
{
    eventHandler(sender, e);
}

Here comes extensions methods to our aid again. With only two extension methods, we can cover all possible event handlers and raise our events safely in one line. For example:

MyEvent.RaiseSafe(this, EventArgs.Empty);

Or

MyEvent.RaiseSafe<MyEventArgs>(this, new MyEventArgs(someParameter));

In order to achieve that, here are the needed extension methods:

public static class Extensions
{
    /// <summary>
    /// Raises the event in a safe way.
    /// </summary>
    /// <param name="eventHandler">The event handler.</param>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    static public void RaiseSafe(this EventHandler eventHandler, object sender, System.EventArgs e)
    {
        if (eventHandler != null)
        {
            eventHandler(sender, e);
        }
    }

    /// <summary>
    /// Raises the event in a safe way.
    /// </summary>
    /// <typeparam name="T">Type of the event handler.</typeparam>
    /// <param name="eventHandler">The event handler.</param>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The event arguments containg that event data.</param>
    static public void RaiseSafe<T>(this EventHandler<T> eventHandler, object sender, T e)
        where T : System.EventArgs
    {
        if (eventHandler != null)
        {
            eventHandler(sender, e);
        }
    }
}

All the best,
Shay

kick it on DotNetKicks.com Shout it

Published Monday, May 25, 2009 2:15 PM by shayf

Comments

# A Handy Extension Method: Raise Events Safely

Thank you for submitting this cool story - Trackback from DotNetShoutout

Monday, May 25, 2009 7:41 PM by DotNetShoutout

# A Handy Extension Method: Raise Events Safely

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Monday, May 25, 2009 7:41 PM by DotNetKicks.com

# re: A Handy Extension Method: Raise Events Safely

The article is ver good. Write please more

Friday, June 12, 2009 8:29 PM by Kelly Brown

# re: A Handy Extension Method: Raise Events Safely

You have a race condition in your first code snippet, since another thread might have unsubscribed from the event after the nullity check. Lol @ that.

Second, your extension method will compile into a normal static method where the event handler will be method-local which takes care of the bug. Somehow though it doesn't seem you realized this... :p

Tuesday, September 22, 2009 12:53 AM by Henrik (MSP)

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: