CSharp examples for Language Basics:Null Operator
In the following example, s evaluates to null, even with a standard dot operator between ToString() and ToUpper():
using System;/* ww w . j av a 2 s. c o m*/ class Test { static void Main(){ System.Text.StringBuilder sb = null; string s = sb?.ToString().ToUpper(); // s evaluates to null without error Console.WriteLine(s); } }
Repeated use of ?. is necessary only if the operand immediately to its left may be null.
The following expression is robust to both x being null and x.y being null:
x?.y?.z
The final expression must be capable of accepting a null.
The following is illegal:
System.Text.StringBuilder sb = null;
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 also use the null-conditional operator to call a void method:
someObject?.SomeVoidMethod();
If someObject is null, this becomes a "no-operation" rather than throwing a NullReferenceException.
Null-conditional operator combines well with the null-coalescing operator:
System.Text.StringBuilder sb = null; string s = sb?.ToString() ?? "nothing"; // s evaluates to "nothing"
The last line is equivalent to:
string s = (sb == null ? "nothing" : sb.ToString());