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
2
a ?? b ?? c
d ??= e ??= f

Are evaluated as

1
2
a ?? (b ?? c)
d ??= (e ??= f)

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
2
3
4
5
6
7
double SumNumbers(List<double[]> setsOfNumbers, int indexOfSetToSum)
{
return setsOfNumbers?[indexOfSetToSum]?.Sum() ?? double.NaN; //?[] will get null if setOfNumbers is null
}

var sum = SumNumbers(null, 0);
Console.WriteLine(sum); // output: NaN

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
2
3
int? a = null;
int b = a ?? -1;
Console.WriteLine(b); // output: -1

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
2
3
4
5
public string Name
{
get => name;
set => name = value ?? throw new ArgumentNullException(nameof(value), "Name cannot be null");
}

Assign value if null

Beginning with C# 8.0, you can use the ??= operator to replace the code of the form

1
2
3
4
if (variable is null)
{
variable = expression;
}

By:

1
variable ??= expression;