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!
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:
Instead you’d have to do:
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.