- X?.Y; //null if X is null else X.Y
- X?.Y?.Z; //null if X is null or Y is null else X.Y.Z
- X?[index]; //null if X is null else X[index]
- X?.ValueMethod(); //null if X is null else the result of X.ValueMethod();
- X?.VoidMethod(); //do nothing if X is null else call X.VoidMethod();
Note that when using the null coalescing operator on a value type
T you will get a
This effect can be chained together:
?. operator is syntactic sugar to avoid verbose null checks. It's also known as the Safe navigation operator.
Class used in the following example:
If an object is potentially null (such as a function that returns a reference type) the object must first be checked for null to prevent a possible
NullReferenceException. Without the null-conditional operator, this would look like:
The same example using the null-conditional operator:
Chaining the Operator
The null-conditional operator can be combined on the members and sub-members of an object.
Combining with the Null-Coalescing Operator
The null-conditional operator can be combined with the null-coalescing operator to provide a default value:
Null-conditional Operator can be used with Extension Method
Extension Method can work on null references, but you can use
?. to null-check anyway.
Normally, the method will be triggered for
null references, and return -1:
?. the method will not be triggered for
null references, and the type is
This behavior is actually expected from the way in which the
?. operator works: it will avoid making instance method calls for null instances, in order to avoid
NullReferenceExceptions. However, the same logic applies to the extension method, despite the difference on how the method is declared.
For more information on why the extension method is called in the first example, please see the Extension methods - null checking documentation.
The Null-Conditional Index
Similarly to the
?. operator, the null-conditional index operator checks for null values when indexing into a collection that may be null.
is syntactic sugar for