August 2, 2012

Generic Event Firer


Here is the common .NET pattern for firing some event
// Here is the event
public event EventHandler<ReminderEventArgs> ReminderOccured;
...
// And to fire it
EventHandler<ReminderEventArgs> reminderOccured = this.ReminderOccured;
if (reminderOccured != null)
{
    reminderOccured(this, new ReminderEventArgs { Reminder = reminder });
}

This is a common pattern so a helper class to tidy this up might be of some use:
public static class EventFirer
{
    public static void FireEvent<TEventArgs>(object firer, 
        EventHandler<TEventArgs> eventToFire, TEventArgs eventargs)
        where TEventArgs : EventArgs
    {
        EventHandler<TEventArgs> eventToFireReference = eventToFire;
        if (eventToFireReference != null)
        {
            eventToFireReference(firer, eventargs);
        }
    }

    public static void FireEvent(object firer, EventHandler eventToFire, 
        EventArgs eventargs)
    {
        EventHandler eventToFireReference = eventToFire;
        if (eventToFireReference != null)
        {
            eventToFireReference(firer, eventargs);
        }
    }
}
With this class firing the event becomes:
EventFirer.FireEvent<ReminderEventArgs>(this, 
    this.ReminderOccured, 
    new ReminderEventArgs { Reminder = reminder });

No comments: