patterncsharpModerate
Checking if an event is not null before firing it in C#
Viewed 0 times
nullcheckingfiringbeforenotevent
Problem
I often see this for custom events:
But is creating the handler variable required, best practice, or superfluous, when compared to:
?
void InvokeCustomEvent(EventArgs e)
{
var handler = CustomEvent;
if (handler != null) handler(this, e);
}But is creating the handler variable required, best practice, or superfluous, when compared to:
void InvokeCustomEvent(EventArgs e)
{
if (CustomEvent != null) CustomEvent(this, e);
}?
Solution
But is creating the handler variable required, best practice, or superfluous, when compared to:
Yes, it is needed. Otherwise,
I usually have this declared somewhere in my codebase:
Now, with any event handler, you can just do:
You can call an extension method with a
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(this EventHandler 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.Code Snippets
public static class EventExtensions
{
public static void Raise<T>(this EventHandler<T> handler, T args) {
if (handler != null) handler(args);
}
}handler.Raise(args);Context
StackExchange Code Review Q#1142, answer score: 15
Revisions (0)
No revisions yet.