C# Language Null fall-through and chaining


Example

The left-hand operand must be nullable, while the right-hand operand may or may not be. The result will be typed accordingly.

Non-nullable

int? a = null;
int b = 3;
var output = a ?? b;
var type = output.GetType();  

Console.WriteLine($"Output Type :{type}");
Console.WriteLine($"Output value :{output}");

Output:

Type :System.Int32
value :3

View Demo

Nullable

int? a = null;
int? b = null;
var output = a ?? b;

output will be of type int? and equal to b, or null.

Multiple Coalescing

Coalescing can also be done in chains:

int? a = null;
int? b = null;
int c = 3;
var output = a ?? b ?? c;

var type = output.GetType();    
Console.WriteLine($"Type :{type}");
Console.WriteLine($"value :{output}");

Output:

Type :System.Int32
value :3

View Demo

Null Conditional Chaining

The null coalescing operator can be used in tandem with the null propagation operator to provide safer access to properties of objects.

object o = null;
var output = o?.ToString() ?? "Default Value";

Output:

Type :System.String
value :Default Value

View Demo