This question already has an answer here:
- Nullable type is not a nullable type? 4 answers
Why is the output of this snippet System.Int32
instead of Nullable<Int32>
?
int? x = 5;
Console.WriteLine(x.GetType());
This question already has an answer here:
Why is the output of this snippet System.Int32
instead of Nullable<Int32>
?
int? x = 5;
Console.WriteLine(x.GetType());
You can't box a nullable.
You could do something like this:
GetType()
isn't virtual, and is thus defined only onobject
. As such, to make the call, theNullable<Int32>
must first be boxed. Nullables have special boxing rules, though, so only theInt32
value is boxed, and that's the type reported.GetType()
is a method ofobject
.To call it, the
Nullable<T>
struct must be boxed.You can see this in the IL code:
Nullable types are treated specially by CLR; it is impossible to have a boxed instance of a nullable type.
Instead, boxing a nullable type will result in a null reference (if
HasValue
is false), or the boxed value (if there is a value).Therefore, the
box System.Nullable<System.Int32>
instruction results in a boxedInt32
, not a boxedNullable<Int32>
.Therefore, it is impossible for
GetType()
to ever returnNullable<T>
.To see this more clearly, look at the following code:
This prints
Because the type of "5" is int.
If you want to detect if a type is nullable, and the underlying type, use something like this: