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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With