C# CONCEPTS
Null-Coalescing assignment C# 8.0
C# 8.0 introduces the null-coalescing assignment operator ??=.
You can use the ??= operator to assign the value of its right-hand operand to its left-hand operand only if the left-hand operand is null.
Prerequisites
Let’s understand null coalescing ?? operator
The operator returns the value of left-hand operand if it’s “not null” otherwise the value of the right-hand operand is evaluated.
- The null coalescing operator was introduced in C# 7.0.
- This operator does not even evaluate the right-hand operand if the left-hand operator is not null.
Example
Let us consider an example of the following program, which covers both scenarios.
1. left-hand operand is null, so the value of 9.11 is evaluated and assigned to the output variable.
2. left-hand operand is not null, so the value of var2 is assessed and assigned to the output variable.
double? var1 = null;
double? var2 = 6.66;
double var3;