Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Event Null Check: Safe Invocation Patterns

Learn how to safely check and invoke C# events to avoid NullReferenceException, including the null-conditional operator, race conditions, and custom accessors.

~4 min readC#
#C# events#NullReferenceException#Thread safety#Delegate invocation
Illustration of a C# event being safely invoked with a null-conditional operator, showing a delegate reference being checked before invocation.

A field-like event with no subscribers is represented by a null delegate field. Calling it directly throws a NullReferenceException. The standard safe way to raise such an event is the null-conditional operator:

csharp
SomethingHappened?.Invoke(this, EventArgs.Empty);

The way you check and invoke events affects thread safety, performance, and how your code behaves under concurrency.

What Happens When an Event Has No Subscribers

A field-like event is backed by a delegate field. When no subscriber has been added, that field is null. Attempting to invoke it directly fails:

csharp
public event EventHandler? SomethingHappened; public void Raise() { SomethingHappened(this, EventArgs.Empty); // NullReferenceException if no subscribers }

The runtime tries to call the delegate's Invoke method, but a null delegate has no method to call.

Before C# 6, the typical guard was an explicit null check:

csharp
public void Raise() { var handler = SomethingHappened; if (handler != null) { handler(this, EventArgs.Empty); } }

This works, but it requires a local variable to avoid a race condition, which we'll examine shortly.

The Null-Conditional Operator for Event Invocation

C# 6 introduced the null-conditional operator ?., which provides a concise way to invoke a field-like event:

csharp
public void Raise() { SomethingHappened?.Invoke(this, EventArgs.Empty); }

For a field-like event, the operator reads the delegate reference once, tests it for null, and calls Invoke only when it is non-null. That makes it equivalent to the explicit local-variable pattern above, but with less code. It is the recommended pattern for most event-raising code.

Thread Safety and the Race Condition

The reason the local-variable pattern exists is a classic race condition. Consider this naive check-then-invoke code:

csharp
public void Raise() { if (SomethingHappened != null) { SomethingHappened(this, EventArgs.Empty); } }

Between the null check and the invocation, another thread could remove the last subscriber, setting the event to null. The invocation then throws a NullReferenceException. The local-variable pattern prevents this by reading the delegate into a local reference once:

csharp
var handler = SomethingHappened; if (handler != null) { handler(this, EventArgs.Empty); }

The invocation uses the local handler, which is guaranteed non-null at the point of the call. The null-conditional operator ?. behaves the same way: it reads the delegate reference once, tests it, and invokes on that same reference. Therefore, ?.Invoke will not throw a NullReferenceException because of a race between checking and invoking.

However, thread safety here does not mean the invocation is atomic with respect to subscriber changes. If another thread removes a subscriber after the delegate reference is captured, that subscriber will still be invoked. That is usually acceptable because the event invocation uses a snapshot of the subscription list at the moment of capture. If you need stricter ordering guarantees, use a different synchronization mechanism, not just a null check.

Custom Add/Remove Accessors

The ?.Invoke shortcut uses the compiler-provided delegate field of a field-like event. When you write custom add and remove accessors, the event is not automatically backed by a field that you can read through the event name. You need to invoke the stored delegate or collection directly.

If the accessors store handlers in a single delegate field, use the same null-conditional pattern on that field:

csharp
private EventHandler? _handlers; public event EventHandler? SomethingHappened { add => _handlers += value; remove => _handlers -= value; } public void Raise() { _handlers?.Invoke(this, EventArgs.Empty); }

If the accessors store handlers in a collection, such as List<EventHandler> or a concurrent collection, write a raise method that iterates over a snapshot of the collection. Copying the handlers to an array before iterating prevents later modifications from affecting the current invocation. If the collection is not thread-safe, synchronize the copy with the same lock used in add and remove. The null-conditional operator is not a substitute for that logic because the event is not represented by a single delegate.

Performance and Allocation Considerations

For a field-like event, the null-conditional operator does not allocate. It tests the delegate and invokes it when non-null. The larger cost is usually invoking subscribers: a multicast delegate with n subscribers is invoked in O(n) time, and each subscriber can do arbitrary work. The null test itself is unlikely to be a bottleneck.

If profiling shows that a frequently raised event is almost always unsubscribed, one alternative is to initialize the event to an empty delegate and invoke it without checking for null:

csharp
public event EventHandler SomethingHappened = delegate { };

That removes the null branch but adds complexity, and it is rarely worth it unless profiling shows a real problem.

Choosing the Right Invocation Pattern

For most field-like events, ?.Invoke is the right choice. It is concise, safe, and idiomatic.

If you need to raise the event later or on another thread, capture a snapshot first. For example, to post to a SynchronizationContext:

csharp
public void RaiseOnUiThread(SynchronizationContext uiContext) { var handler = SomethingHappened; if (handler != null) { uiContext.Post(_ => handler(this, EventArgs.Empty), null); } }

The local snapshot avoids the race between the null check and the later invocation, and it captures the subscribers that were present when Raise was called. The same local-snapshot approach applies if you hand the delegate to Task.Run or another deferred execution site.

If you are using custom accessors with a collection of handlers, use a raise method that iterates over a snapshot of the collection, and handle per-subscriber exceptions if needed.

These patterns keep event invocation null-safe without requiring a visible null check at every call site.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.