HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Checking if an event is not null before firing it in C#

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
nullcheckingfiringbeforenotevent

Problem

I often see this for custom events:

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