I have seen a few mentions of this idiom (including on SO):
// Deliberately empty subscriber
public event EventHandler AskQuestion = delegate {};
The upside is clear - it avoids the need to check for null before raising the event.
However, I am keen to understand if there are any downsides. For example, is it something that is in widespread use and is transparent enough that it won't cause a maintenance headache? Is there any appreciable performance hit of the empty event subscriber call?
For systems that make heavy use of events and are performance-critical, you will definitely want to at least consider not doing this. The cost for raising an event with an empty delegate is roughly twice that for raising it with a null check first.
Here are some figures running benchmarks on my machine:
And here is the code I used to get these figures:
Instead of "empty delegate" approach one can define a simple extension method to encapsulate the conventional method of checking event handler against null. It is described here and here.
I would say it's a bit of a dangerous construct, because it tempts you to do something like :
If the client throws an exception, the server goes with it.
So then, maybe you do:
But, if you have multiple subscribers and one subscriber throws an exception, what happens to the other subscribers?
To that end, I've been using some static helper methods that do the null check and swallows any exception from the subscriber side (this is from idesign).
The only downside is a very slight performance penalty as you are calling extra empty delegate. Other than that there is no maintenance penalty or other drawback.
It is my understanding that the empty delegate is thread safe, whereas the null check is not.
Instead of inducing performance overhead, why not use an extension method to alleviate both problems:
Once defined, you never have to do another null event check again: