For Answers, see/post comments

Why do I need a null test before I invoke a delegate?

Ques: Why do I need a null test before I invoke a delegate?

Ans: If you have an event in a class, you need to add a null test before you call the delegate.
Typically, you would write:

if (Click != null)
Click(arg1, arg2);


There is actually a possible race condition here - the event can be cleared between the first and second line. You would actually want to write:

ClickHandler handler = Click;
if (handler != null)
handler(arg1, arg2);


usually. You might want to do some other sort of synchronization in other scenarios.
So back to the main question. Why is the null test required?


We can't change the existing behavior of calling through a delegate as some apps may depend on it, so it would have to be an addition to the language.

We have talked about adding an Invoke() keyword to the language to make this easier, but after a fair bit of discussion, we decided that we couldn't do the right thing all the time, so we elected not to do anything.

No comments: