Firing events with Extension Methods
OK, sometimes you have an idea that is one point (seemingly) brilliant, simple, and kind of stupid all in one shot. This is one of those. Actually, I’m still trying to figure out if this is really a good idea or not — and what better way to do that than to post the idea on a blog and strike a flame war! Bring it on.
Lets start with the standard model for creating and firing events.
Step 1: Create the event
public eventEventHandler<EventArgs> OnLoadData;
My current method is to always use the generic EventHandler<> instead of the old-school EventHandler. I think it makes for better-looking code IMHO.
Step 2: Fire the Event (Old Skool)
1: if(OnLoadData != null) 2: { 3: OnLoadData(this, null); 4: }
Step 3: We can do better
There is a cool feature that you get with extension methods: you can call an extension method on null base object! So you can now do things that were impossible – like removing a null check when firing an event and just fire the event!
Step 4: Create an extension method
To start you have to create a static class and … oh forget it, here is the code.
1: using System; 2: 3: namespaceMyNamespace 4: { 5: public static classMyExtensions 6: { 7: public static voidFire<TEventArgs>( thisEventHandler<TEventArgs> myEvent, objectsender, TEventArgs e) whereTEventArgs: EventArgs 8: { 9: if(myEvent != null) 10: myEvent(sender, e); 11: } 12: } 13: }
Step 5: Refactor Step 2
1: OnLoadData.Fire(this, null);
Done.
Step 6: Profit
Well, I will as soon as I figure out how. I mean really, I save 3 friggen lines of code here. Big deal–right? Well, There are some moral victories in this.
- I simplified the firing of events ever so slightly by removing previously mandatory logic.
- It is reusable. The Fire extension method can be used with any event that we create with the generic EventHandler.
- I have added an ever so small amount of clarity to what the code is doing. Granted, this will only clear things up for the extreme noob or clueless manager who wants to see the code…but still. Let’s not be snobby about this.
- I figured out a grand way to use and abuse Extension Methods in a useful way. It makes me feel special. What can I say.
- And I like it. Something about always having to check if the EventHander was null -EVERY SINGLE TIME I WANTED TO JUST FIRE A FREEKING EVENT- bugged me for some inexplicable reason. This little hack sets my soul at ease. So there.


