Safely firing an event, Part 2

A while back I wrote about Safely firing an event.

 

I come to you now with another solution to the problem, which I like quite a bit more.

 

In Properties with events: another attempt, we tried initializing an event with an empty anonymous method. It works, but there’s always a risk that one of your constructors won’t do the right thing.

 

It turns out that you can use a field initializer on an event. I don’t know why I didn’t try this yesterday, its seems obvious now!

 

            public event System.EventHandler MyEvent = delegate { };

 

                  c.MyEvent(this, EventArgs.Empty); // no null check required!

Voila! The event will never be null.

 

There may be a small perf hit, but until my perf analysis tells me that this specific instance is a perf problem, I’m fine as-is.

 

If your class wants to check if there are any listeners, it can no longer do:

 

                  if (c.MyEvent == null)

                  {

                        // no one listens to me.

                  }

 

Instead you’d have to do:

 

                  // 1 because it always contains the empty delegate

                  if (c.MyEvent.GetInvocationList().Length == 1)

                  {

                        // no one listens to me.

                  }

 

If I am ever inclined to write such code, I will first think about changing my design so the problem goes away, and second do some Extract Method Refactorings to hide the nasty bits.