Usually the answers to such questions can be found here or, if not here, on MSDN, but I looked and looked and did not find the answer. The experiment seems to show code like:
SomeControl.Click += null;
does no harm. Or, at least, what fires the event does not throw an exception (I can say), trying to call a null event listener. Nevertheless, it seems that there is nowhere on the Web that confirms my hope that such code does not do at least what I may not want to do. For example, triggering a Click event to think that it has listeners when it might be wrong, and spend those precious super-ultra-mini-microseconds on "now allow you to perform null checks and call all listeners that are not null" code.
It seems that the documentation should say that the behavior of the operators + = and - = if the listener on the RHS is null. But, as I said, I can not find this documentation anywhere. I'm sure someone here can provide this, though ....
(Obviously, my code does not have hardcoded zero, my question is whether such code is wasteful or completely safe:
public static void AddHandlers([NotNull] this Button button,
[CanBeNull] EventHandler click = null,
[CanBeNull] EventHandler load = null)
{
button.Click += click;
button.Load += load;
}
or if I need (that is, for some reason) add null checks around each such operation + =.)
source
share