CSharp examples for Language Basics:Nullable
Nullable types work well with the ?? operator.
For example:
using System;/* w ww . ja v a2s. co m*/ class Test { static void Main() { int? x = null; int y = x ?? 5; // y is 5 int? a = null, b = 1, c = 2; Console.WriteLine (a ?? b ?? c); // 1 (first non-null value) } }
In the following example, length evaluates to null:
System.Text.StringBuilder sb = null; int? length = sb?.ToString().Length;
We can combine this with the null-coalescing operator to evaluate to zero instead of null:
int length = sb?.ToString().Length ?? 0; // Evaluates to 0 if sb is null