20

In C#, if I write

int? x = null;
x += x ?? 1

I would expect this to be equivalent to:

int? x = null;
x = x + x ?? 1

And thus in the first example, x would contain 1 as in the second example. But it doesn't, it contains null. The += operator doesn't seem to work on nullable types when they haven't been assigned. Why should this be the case?

Edit: As pointed out, it's because null + 1 = null and operator precedence. In my defence, I think this line in the MSDN is ambiguous!:

The predefined unary and binary operators and any user-defined operators that exist for value types may also be used by nullable types. These operators produce a null value if [either of] the operands are null; otherwise, the operator uses the contained value to calculate the result.

Zac
  • 1,722
  • 1
  • 19
  • 22

1 Answers1

33

Here is the difference between the two statements:

x += x ?? 1
x = (x + x) ?? 1

The second isn't what you were expecting.

Here's a breakdown of them both:

x += x ?? 1
x += null ?? 1
x += 1
x = x + 1
x = null + 1
x = null

x = x + x ?? 1
x = null + null ?? 1
x = null ?? 1
x = 1
Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
  • 7
    +1 Ah, operator precedence, my ancient foe. You strike again! – JDB Oct 03 '12 at 15:42
  • Doesn't `??` have precedence over `+`? (@Servy's answer) – Austin Salonen Oct 03 '12 at 15:44
  • 2
    Ah, I failed to appreciate that null + 1 = null. Missed this line in the MSDN: The predefined unary and binary operators and any user-defined operators that exist for value types may also be used by nullable types. These operators produce a null value if the operands are null; otherwise, the operator uses the contained value to calculate the result. – Zac Oct 03 '12 at 16:04