Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 382
LCIII Avatar asked Sep 11 '25 23:09

LCIII


1 Answers

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.

like image 98
LCIII Avatar answered Sep 14 '25 12:09

LCIII