why is typeof int? an Int32
int? x = 1;
Console.WriteLine(x.GetType().Name);
If it is okay then what\'s the use of
Calling GetType() boxes your variable. The CLR has a special rule that Nullable gets boxed to T. So x.GetType will return Int32 instead of Nullable.
int? x = 1;
x.GetType() //Int32
typeof(int?) //Nullable
Since a Nullable containing null will be boxed to null the following will throw an exception:
int? x = null;
x.GetType() //throws NullReferenceException
To quote MSDN on Boxing Nullable Types:
Objects based on nullable types are only boxed if the object is non-null. If
HasValueisfalse, the object reference is assigned tonullinstead of boxingIf the object is non-null -- if
HasValueistrue-- then boxing occurs, but only the underlying type that the nullable object is based on is boxed. Boxing a non-null nullable value type boxes the value type itself, not theSystem.Nullablethat wraps the value type.