Possible Duplicate:
Nullable type is not a nullable type?
In the following code:
DateTime? dt = DateTime.Now;
MessageBox.Show(dt.GetType().ToString());
the message box shows "System.DateTime", instead of Nullable<DateTime>
. The following also returns false (because the GetType is wrong):
if (dt.GetType().IsAssignableFrom(typeof(DateTime?)))
...
(btw, using DateTime?
or Nullable<DateTime>
doesn't make a difference)
In the watch window, you have the "Type" column that's displaying the correct type (System.DateTime?).
In my code I have reference to dt as an object
, so I need to get to the underlying type correctly. How can I do this?
Quoting MSDN (How to: Identify a Nullable Type):
Calling GetType on a Nullable type causes a boxing operation to be performed when the type is implicitly converted to Object. Therefore GetType always returns a Type object that represents the underlying type, not the Nullable type.
so basically your code is equal to:
DateTime? dt = DateTime.Now;
object box = (object)dt;
Console.Write(box.GetType().ToString());
also, looking at "Boxing Nullable Types" on MSDN we read:
If the object is non-null -- if HasValue is true -- 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 the System.Nullable(Of T) that wraps the value type.
this clearly explain the "strange" behavior of Nullable<T>.GetType()
GetType()
uses reflection to return a type. To find out if it's a nullable type you need to check the PropertyType
value.
foreach (PropertyInfo pi in dt.GetType().GetProperties())
{
if(pi.PropertyType == typeof(DateTime?))
{
// display nullable info
}
}
Because if you write something like this:
DateTime? dt = null; Type t = dt.GetType();
It was a NullReferenceException.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With