Why doesn't incrementing Nullable<int> throw an exception?

Could you please explain, why does Console.WriteLine write empty line (Console.WriteLine(null) give me compilation error) and why there isn't NullReferenceException (even a+=1 shouldn't raise it)?

int? a = null;
a++; // Why there is not NullReferenceException? 
Console.WriteLine(a); // Empty line
Jon Skeet
people
quotationmark

You're observing the effects of a lifted operator.

From section 7.3.7 of the C# 5 specification:

Lifted operators permit predefined and user-defined operators that operate on non-nullable value types to also be used with nullable forms of those types. Lifted operators are constructed from predefined and user-defined operators that meet certain requirements, as described in the following:

  • For the unary operators + ++ - -- ! ~ a lifted form of an operator exists if the operand and result types are both non-nullable value types. The lifted form is constructed by adding a single ? modifier to the operand and result types. The lifted operator produces a null value if the operand is null. Otherwise, the lifted operator unwraps the operand, applies the underlying operator, and wraps the result.

So basically, a++ in this case is an expression with a result of null (as an int?) and the variable is left untouched.

When you call

Console.WriteLine(a);

that's being boxed into object, which converts it to a null reference, which is printed as an empty line.

people

See more on this question at Stackoverflow