Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The += operator with nullable types in C#

Tags:

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.

like image 391
Zac Avatar asked Oct 03 '12 15:10

Zac


1 Answers

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
like image 170
Kendall Frey Avatar answered Sep 23 '22 03:09

Kendall Frey