O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required