How will you make it if you never even try?

April 3, 2009

C# Event handlers: a good idea immediately superseded by a BETTER one

Filed under: C# — charlieflowers @ 12:39 am

When you have events in C#, you need to check to make sure they’re not null before firing them. They will be null if no one has ever registered for the event before. So you gotta do this:

namespace ConsoleApplication1
{
  class Program
  {
    public event EventHandler<EventArgs> someEvent;
    
    static void Main(string[] args)
    {
      // Imagine something happened, need to fire event
      if(someEvent != null) // Don't forget this vital null check!
         someEvent(this, EventArgs.Empty);
    } 

If you forget the null check, you will get a null reference exception if no one has registered for your event.

So here’s the “only good idea” (to be superseded below with the “great idea”)

The “only good idea” is to add an empty delegate to the event immediately when you declare it. Like this:

public event EventHandler<EventArgs> someEvent = delegate {};

I used to think that was a fabulous idea. After all, it has a lot of benefits. Now, you can freely just fire the event. The only overhead is that it will always call your empty delegate, which is the overhead of one unnecessary method call (not usually a big deal).

But here’s the better idea: Define an Extension Method on EventHandler that does the null check for you!

This is better because it is more readable and because it gets rid of that slight performance overhead of the empty delegate.

Here’s how:

public static void Fire<T>(this EventHandler<T> self, object sender, T args) where T : EventArgs
{
   if(self != null) self(sender, args);
}

Then, when it is time to fire an event, you do this:

someEvent.Fire(this, EventArgs.Empty);

I love it. You see, what is happening here is that, even though much of the community knows the new C# 3.0 language features pretty well, we continue to find new, powerful, delightful ways to use them.

By the way, the first place I learned this technique was from this question on StackOverflow.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: