I was taking the LINQ course on Udemy and I came across new operators: ?? and ??=.
??
The null-coalescing operator ?? returns the value of its left-hand operand if it isn’t null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn’t evaluate its right-hand operand if the left-hand operand evaluates to non-null.
??=
Available in C# 8.0 and later, the null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null. The ??= operator doesn’t evaluate its right-hand operand if the left-hand operand evaluates to non-null.
Right-Associative
The null-coalescing operators are right-associative. That is, expressions of the form
1 | a ?? b ?? c |
Are evaluated as
1 | a ?? (b ?? c) |
Usage
Giving a default value when null-conditional operations evaluate to null
In expressions with the null-conditional operators ?. and ?[], you can use the ?? operator to provide an alternative expression to evaluate in case the result of the expression with null-conditional operations is null.
This is how the Udemy course uses it:
Another example from Microsoft Docs:
1 | double SumNumbers(List<double[]> setsOfNumbers, int indexOfSetToSum) |
Work with nullable value types
When you work with nullable value types (T?) and need to provide a value of an underlying value type, use the ?? operator to specify the value to provide in case a nullable type value is null:
1 | int? a = null; |
Throw exception on null values
Beginning with C# 7.0, you can use a throw expression as the right-hand operand of the ?? operator to make the argument-checking code more concise:
1 | public string Name |
Assign value if null
Beginning with C# 8.0, you can use the ??= operator to replace the code of the form
1 | if (variable is null) |
By:
1 | variable ??= expression; |