.net alternatives

by Michel Grootjans
posts - 50, comments - 84, trackbacks - 1

My Links

News

Shelfari: Book reviews on your book blog

Twitter












Archives

Post Categories

Elegant way to raise an event

I got fed up with this kind of code for a long time:

private void personList_DoubleClick(object sender, EventArgs e)
{
    if (ShowSelectedPerson != null)
        ShowSelectedPerson(this, EventArgs.Empty);
}

Today, a colleague of mine triggered this simple idea:

private void personList_DoubleClick(object sender, EventArgs e)
{
    ShowSelectedPerson.Raise(this, EventArgs.Empty);
}

This is implemented with a simple extension method

public static class EventHandlerExtensions
{
    public static void Raise(this EventHandler eventHandler, object sender, EventArgs eventArgs)
    {
        if (eventHandler.IsNotNull())
            eventHandler(sender, eventArgs);
    }
}

Damn, I love extension methods!

Print | posted on Monday, January 19, 2009 1:24 PM |

Feedback

Gravatar

# re: Elegant way to raise an event

hi michel,

nice idea, but shouldnt you copy the eventhandler to be thread save?
like this:

public static class EventHandlerExtensions
{
public static void Raise(this EventHandler eventHandler, object sender, EventArgs eventArgs)
{
EventHandler tmp = eventHandler; // make copy, so it is save when a different thread changes it
if (tmp != null)
tmp(sender, eventArgs);
}
}

happy coding.

basti aka batteryslave
1/19/2009 3:41 PM | basti
Gravatar

# re: Elegant way to raise an event

Hi michel,

very nice way!
When I see some cool extension methods, I think: Damn, this could have been my idea!

Regards, Dirk
1/19/2009 4:33 PM | Dirk Rodermund
Gravatar

# re: Elegant way to raise an event

Is it sad that I find this beautiful. I love the simplicity, and I can see lots of opportunities to use it too.

Thanks

Dean
1/23/2009 3:18 PM | Dean Collins
Gravatar

# re: Elegant way to raise an event

try this instead:

public event EventHandler ShowSelectedPerson = delegate { };


Now theres no need to check if its null before firing it.
1/26/2009 2:27 PM | SGreene
Gravatar

# re: Elegant way to raise an event

@ SGreene

You're right, and that's exactly what I did up until now. The only difference is that you have to think about that trick every time.

With this extension method, you don't have to think about it anymore.
1/26/2009 2:34 PM | Michel Grootjans
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 

Powered by: