What is the double question mark equals sign (??=) in C#?

12.7k views Asked by At

I've been seeing statements like this a lot:

int? a = 5;

//...other code

a ??= 10;

What does the ??= mean in the second line? I've seen ?? used for null coalescing before, but I've never seen it together with an equals sign.

1

There are 1 answers

0
LCIII On BEST ANSWER

It's the same as this:

if (a == null) {
  a = 10;
}

It's an operator introduced in C# 8.0: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator

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.