Geeks With Blogs

News
Shelfari: Book reviews on your book blog

.net alternatives by Michel Grootjans

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!

Posted on Monday, January 19, 2009 1:24 PM | Back to top


Comments on this post: Elegant way to raise an event

# re: Elegant way to raise an event
Requesting Gravatar...
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
Left by basti on Jan 19, 2009 3:41 PM

# re: Elegant way to raise an event
Requesting Gravatar...
Hi michel,

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

Regards, Dirk
Left by Dirk Rodermund on Jan 19, 2009 4:33 PM

# re: Elegant way to raise an event
Requesting Gravatar...
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
Left by Dean Collins on Jan 23, 2009 3:18 PM

# re: Elegant way to raise an event
Requesting Gravatar...
try this instead:

public event EventHandler ShowSelectedPerson = delegate { };


Now theres no need to check if its null before firing it.
Left by SGreene on Jan 26, 2009 2:27 PM

# re: Elegant way to raise an event
Requesting Gravatar...
@ 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.
Left by Michel Grootjans on Jan 26, 2009 2:34 PM

Your comment:
 (will show your gravatar)


Copyright © Michel Grootjans | Powered by: GeeksWithBlogs.net