11

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.

LCIII
  • 3,102
  • 3
  • 26
  • 43
  • Using `var` here is ambiguous because the reader can't know if you meant `int` or `int?`. The former would make `a ??= 10` useless. – Andrew H Sep 14 '21 at 17:00
  • 3
    I'm unsure whether to flag this... Given that you answered this within seconds of opening it, and that it's an obvious duplicate, it looks like you opened it just to get some upvotes (you don't get any rep for accepting a self-answer) – canton7 Sep 14 '21 at 17:06
  • @canton7 Well, I was scouring SO for an answer to this and couldn't find it until I came across the doc in MSDN. The linked answer was the first to come up but it doesn't even contain the text `??=` in it, nor does it answer the question here. And I answered my own question by checking the "answer your own question" checkbox under the question area. – LCIII Sep 14 '21 at 17:28
  • @canton7 I was mistaken. After some scrolling I found there is an existing answer there! https://stackoverflow.com/a/60620993/1439748 – LCIII Sep 14 '21 at 17:30
  • Well, it's the case with (almost?) all operators that `x op= y` is the same `x = x op y` (although `x` is only evaluated once). My suspicion is just that you self answered straight away, so you posted a question you already knew the answer to – canton7 Sep 14 '21 at 18:31
  • 3
    @canton7 Correct, I self answered in the same form in which I asked the question. I assume that's what that "answer your own question" feature is for? And the whole reason I did all this in the first place was because while the other question asks about ??, it doesn't specifically ask about ??= which I thought was different enough to warrant it's own question. – LCIII Sep 14 '21 at 20:51

1 Answers1

32

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.

LCIII
  • 3,102
  • 3
  • 26
  • 43