But is creating the handler variable required, best practice, or superfluous, when compared to:
Yes, it is needed. Otherwise, CustomEvent
could be set to null
after you've checked for null
, but before you've invoked it. This can happen if it gets set in another thread, or if one of the event handlers unregisters itself or another one.
I usually have this declared somewhere in my codebase:
public static class EventExtensions
{
public static void Raise<T>(this EventHandler<T> handler, T args) {
if (handler != null) handler(args);
}
}
Now, with any event handler, you can just do:
handler.Raise(args);
You can call an extension method with a null
this, so it will do the right thing even if handler
is null
. Furthermore, by copying handler
into the local variable used by Raise
, you automatically get the copy you need to make sure the handler won't disappear under you. Works like a charm.