CSharp - null conditional Operator

Introduction

?. operator is the null-conditional or "Elvis" operator.

?. operator calls methods and access members like the standard dot operator.

If the operand on the left is null, the expression evaluates to null instead of throwing a NullReferenceException:

string sb = null;
string s = sb?.ToString();  // No error; s instead evaluates to null

The last line is equivalent to:

string s = (sb == null ? null : sb.ToString());

null conditional operator short-circuits the remainder of the expression.

string sb = null;
string s = sb?.ToString().ToUpper();   // s evaluates to null without error

The following expression deals with situation where both x being null and x.y are null:

x?.y?.z

The final expression must be capable of accepting a null. The following is illegal:

int length = sb?.ToString().Length;   // Illegal : int cannot be null

We can fix this with the use of nullable value types.

int? length = sb?.ToString().Length;   // OK : int? can be null

You can use the null-conditional operator to call a void method:

sb?.SomeVoidMethod();

If sb is null, this becomes a "no-operation" rather than throwing a NullReferenceException.

You can use null conditional Operator with the null coalescing operator:

string s = sb?.ToString() ?? "nothing";   // s evaluates to "nothing"

Related Topics