Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't attempting to add to a null value throw an InvalidOperationException?

Tags:

c#

.net

int? x = null;
x = x + 1;  // Works, but x remains null

I would expect the compiler to attempt to cast x as an int, but apparently it does not.

Edit by 280Z28: Changed NullReferenceException to InvalidOperationException, which is what Nullable<T>.Value throws when HasValue is false.

like image 356
newdayrising Avatar asked Jan 28 '10 16:01

newdayrising


2 Answers

This is per the specification for lifted binary operators. From §7.2.7:

For the binary operators

+ - * / % & | ^ << >>

a lifted form of an operator exists if the operand and result types are all non-nullable value types. The lifted form is constructed by adding a single ? modifier to each operand and result type. The lifted operator produces a null value if one or both operands are null (an exception being the & and | operators of the bool? type, as described in §7.10.3). Otherwise, the lifted operator unwraps the operands, applies the underlying operator, and wraps the result.

The reasoning is this: you are to think of null for a nullable type as meaning "I do not know what the value is." What is the result of "I don't know" plus one? "I don't know." Thus, the result should be null.

like image 130
jason Avatar answered Oct 15 '22 23:10

jason


Nullables are never actually null references. They are always object references. Their internal classes override the == and = operators. If they are being compared to null, they'll return the value of the HasValue property.

like image 37
rusty Avatar answered Oct 15 '22 23:10

rusty