C# Language ?. (Null Conditional Operator)


Example

6.0

Introduced in C# 6.0, the Null Conditional Operator ?. will immediately return null if the expression on its left-hand side evaluates to null, instead of throwing a NullReferenceException. If its left-hand side evaluates to a non-null value, it is treated just like a normal . operator. Note that because it might return null, its return type is always a nullable type. That means that for a struct or primitive type, it is wrapped into a Nullable<T>.

var bar = Foo.GetBar()?.Value; // will return null if GetBar() returns null
var baz = Foo.GetBar()?.IntegerValue; // baz will be of type Nullable<int>, i.e. int?

This comes handy when firing events. Normally you would have to wrap the event call in an if statement checking for null and raise the event afterwards, which introduces the possibility of a race condition. Using the Null conditional operator this can be fixed in the following way:

event EventHandler<string> RaiseMe;
RaiseMe?.Invoke("Event raised");