Wednesday, October 29, 2008

c# Event null checking

I've always considered having to check an event to see if it's null (because it has no listeners) a flaw in C#. I'm guessing it aids performance as you don't need to construct an event args object if no one is going to consume it.

Anyway, for the most of us, here's some extension methods that allow you to Fire an event and hide away the null checking:


public static class EventHandlerExtentions
{
public static void Raise(this EventHandler handler, object sender)
{
Raise(handler, sender, EventArgs.Empty);
}

public static void Raise(this EventHandler handler, object sender, EventArgs args)
{
if (handler != null)
{
handler(sender, args);
}
}

public static void Raise(this EventHandler handler, object sender, TA args)
where TA : EventArgs
{
if (handler != null)
{
handler(sender, args);
}
}
}


UPDATE:

The simpler alternative is to add an empty delegate when declaring an event:

event MyEvent = delegate {}

No comments: