简体   繁体   中英

The += operator with nullable types in C#

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM