the home row

the home row | Firing Events - Don’t repeat yourself

Firing Events - Don’t repeat yourself

by Rob 12. June 2010 20:25

I've been working on a Silverlight application recently that has a provider layer which exposes lots of events. It became clear pretty quickly that we were violating DRY by using the same pattern again and again to fire the events. Here's a typical piece of code to fire one of the events:

private void OnMapLocationChange(Location location)
{
    var handler = this.MapLocationChanged;

    if (handler != null)
    {
        handler(this, new MapLocationChangeEventArgs(location));
    }
}

The method assigns the event handler to a local variable, which stops problems with the handler being nulled whilst the method is executing. It then checks that the handler isn't null. And then finally calls the event handler to fire the event with a new EventArgs object.

Looking at these methods the only thing that differed was the type of event they dealt with. The duplication can be removed easily with a generic method. The method takes the event handler that will be called. We don't need to know the type of the event until compile time so we can set it to be generic. We then add a Func delegate which has the responsibility of creating the event argument. The event argument could have been passed in directly but this would mean that the object was constructed unnecessarily if the event handler is null. Here's the method I came up with.

public static void FireEvent<T>(this EventHandler<T> eventHandler, object sender, Func<T> createEventArgs)
    where T : EventArgs
{
    var handler = eventHandler;

    if (handler != null)
    {
        handler(sender, createEventArgs());
    }
}

You've probably noticed that it's an extension method. I've used an extension method so we can hang it straight off the event handler which gives us this very tidy option for firing the events:

this.MapLocationChanged.FireEvent(this, () => new MapLocationChangedEventArgs(location));

Tags:

Comments

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen