?. and ?[] null-conditional Operators (C# and Visual Basic)

Tests the value of the left-hand operand for null before performing a member access (?.) or index (?[]) operation; returns null if the left-hand operand evaluates to null.

These operators help you write less code to handle null checks, especially for descending into data structures.

int? length = customers?.Length; // null if customers is null   
Customer first = customers?[0];  // null if customers is null  
int? count = customers?[0]?.Orders?.Count();  // null if customers, the first customer, or Orders is null  
Dim length = customers?.Length  ' null if customers is null  
Dim first as Customer = customers?(0)  ' null if customers is null  
Dim count as Integer? = customers?(0)?.Orders?.Count()  ' null if customers, the first customer, or Orders is null  

The null-conditional operators are short-circuiting. If one operation in a chain of conditional member access and index operation returns null, then the rest of the chain’s execution stops. In the following example, E doesn't execute if A, B, or C evaluates to null.

A?.B?.C?.Do(E);
A?.B?.C?[E];
A?.B?.C?.Do(E);
A?.B?.C?(E);

Another use for the null-conditional member access is invoking delegates in a thread-safe way with much less code. The old way requires code like the following:

var handler = this.PropertyChanged;  
if (handler != null)  
    handler(…);
Dim handler = AddressOf(Me.PropertyChanged)  
If handler IsNot Nothing  
    Call handler(…)  

The new way is much simpler:

PropertyChanged?.Invoke(…)  
PropertyChanged?.Invoke(…)

The new way is thread-safe because the compiler generates code to evaluate PropertyChanged one time only, keeping the result in a temporary variable. You need to explicitly call the Invoke method because there is no null-conditional delegate invocation syntax PropertyChanged?(e).

Language Specifications

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

For more information, see the Visual Basic Language Reference.

See Also

?? (null-coalescing operator)
C# Reference
C# Programming Guide
Visual Basic Programming Guide