"rubikzube*" <th************@gmail.com> wrote:
I'm trying to write a snippet of code to detect if a variable is a
nullable<t> struct, and I can't figure out the right syntax or if such
a thing is even possible... Below are the results that I got when I
attempted to perform some simple tests.
Either the variable is declared to be of type Nullable<T> (aka T?), or it
is stored in an object reference. The implementation of nullables in the
CLR is such that it is impossible to have a boxed nullable on the heap.
That is:
int? x = 4;
object o = x;
Console.WriteLine(o.GetType().Name);
should result in System.Int32 being printed to the console. The reason is
that when the CLR tries to box an instance of Nullable<T>, it looks at the
value inside the nullable struct. If the value is null, it boxes to a null
reference. If it isn't null, it gets boxed as the inner value of type T.
So, given a reference to a (possibly boxed struct) object of unknown type,
it is impossible for it to be an instance of Nullable<T>.
I also tried reflecting through the code and walking through the
documentation, but there doesn't seem to be any method of detecting if
a variable is a nullable struct. Does anyone know how to do this?
By design (and because of a late DCR (design change request)) between .NET
2.0 Beta 2 and .NET RTM, boxed nullables cannot occur.
The rational is that a boxed null is unintuitive. For example, with Beta
2, the following code would print 'True' followed by 'False':
int? x = null;
Console.WriteLine(x == null);
object o = x;
Console.WriteLine(o == null);
This was unintuitive, because the o reference wasn't null, it was pointing
to a boxed Nullable<int> instance whose value was null. This caused too
much confusion, so the CLR was modified to ensure that any attempt to box
a Nullable<T> resulted either in a null reference or a boxed instance of
T.
-- Barry