4. juni 2009 05:43
lea
Tired of "OnEvent", just fire already!
I've been writing one too many protected void OnThisEvent() and OnThatEvent() handlers lately, and what's bugging me the most is having to if (Event != null) every time.
So I wrote a wee little helper giving me just a wee bit less code to write when I want to fire an(y) event.
Trick is it has to be used from the exact class (even if the event is in the base class) the event is declared, so you still need protected void OnThisEvent() for base classes to fire it, but it's still a bit neater I think. It kind of says "I'm telling my observers this happened" instead of "I might be doing something now". :)
(Of course encapsulating the event firing in a common method as OnEvent() is also necessary when anything else than firing the event should be done)
Here's the class:
public static class Fire
{
public static object Event(Delegate theDelegate, params object[] args)
{
if (theDelegate != null)
return theDelegate.DynamicInvoke(args);
return null;
}
}
And here's some code showing it off..
// Forwarding "menu" click to presenter
protected void repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
Fire.Event(NavigatingTo, this, new NavigatingEventArgs(e.Item.ItemIndex));
}
// Exposing event to derived classes
protected void OnViewInitialized()
{
Fire.Event(ViewInitialized, this, EventArgs.Empty);
}
// Which is just a wee bit cooler than...
protected void OnViewInitialized()
{
if (ViewInitialized != null)
ViewInitialized(this, EventArgs.Empty);
}
Filed under: C#, Utilities