Raising Events, the Correct Way

In our CountDown example, you’ve seen how to raise events using this pattern:

if (Tick != null)    Tick(n);

Looks right, doesn’t it? If nobody is listening for the event, Tick is null, and we should not attempt to invoke the delegate because that will cause the runtime to yell at us with a NullReferenceException.

Note: Why Is Null Used Anyway?

It might be surprising that the empty event handlers are being presented with null references. This is really due to the way the Combine and Remove methods on Delegate are implemented, but that just pushes the question further out: Why not just return a MulticastDelegate with an empty invocation list?

If we were to do that, the compiler should make sure that every event ...

Get C# 5.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.