The Nullable Conundrum
I've done my share of development where we resorted to use int.MinValue or DateTime.MinValue to represent a null value from the database, and then make the necessary behavior changes in the busineess logics to deal with it. Another path is to wrap these values using a struct. Either way, it is quite a hassle.
Now with .Net 2.0, we got the System.Nullable type. And coupled with generics, suddenly we can say hello to int? or DateTime?, which is a short hand representation for System.Nullable<T>.
Now here's a conundrum.
If we do the following:
int? i = 1;
object o = i; //boxing
int? j = o as int?; //unboxing
will it compile?
The answer is YES! Curiously, the "as" operand can be applied to nullable types.
The IL emmitted is nothing special, it does an "isinst" test before unboxing it.
But why the "isinst" operand can be applied to a nullable type, which in essence is a struct?
The following will not compile:
int? i = 1;
object o = i;
int j = o as int; //the as operator must be used with a reference type
The answer could lie within the way the CLR treats nullable type itself.
A few good read from MSDN and this posting in Somasegar's blog: http://blogs.msdn.com/somasegar/archive/2005/08/11/450640.aspx shed some lights.
But I have yet to find any documentation that states why I can use the "as" operand for nullable types.
From here, we can perform some wonderful boxing gymastics:
int? i = 1;
object o = i;
We can:
int? j = o as int?;
or
int j = (int) o; //will cause a runtime error if i is initialized to null
Also:
int i = 1;
object o = i;
int? j = o as int?;
However,
int? i = null;
object o = i; //o is now a null reference, not a boxed int
It will take a while to get used to these.





