How is the boxing/unboxing behavior of Nullable possible?

There are two things going on:

1) The compiler treats “null” not as a null reference but as a null value… the null value for whatever type it needs to convert to. In the case of a Nullable<T> it’s just the value which has False for the HasValue field/property. So if you have a variable of type int?, it’s quite possible for the value of that variable to be null – you just need to change your understanding of what null means a little bit.

2) Boxing nullable types gets special treatment by the CLR itself. This is relevant in your second example:

    int? i = new int?();
    object x = i;

the compiler will box any nullable type value differently to non-nullable type values. If the value isn’t null, the result will be the same as boxing the same value as a non-nullable type value – so an int? with value 5 gets boxed in the same way as an int with value 5 – the “nullability” is lost. However, the null value of a nullable type is boxed to just the null reference, rather than creating an object at all.

This was introduced late in the CLR v2 cycle, at the request of the community.

It means there’s no such thing as a “boxed nullable-value-type value”.

Leave a Comment