Raising Events, the Correct Way

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

image

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

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

Get C# 4.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.