Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is GetType() returning DateTime type for Nullable<DateTime> [duplicate]

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?

like image 536
veljkoz Avatar asked Jan 21 '11 13:01

veljkoz


3 Answers

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()

like image 117
digEmAll Avatar answered Nov 02 '22 22:11

digEmAll


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
    }
}
like image 23
John K. Avatar answered Nov 02 '22 23:11

John K.


Because if you write something like this:

DateTime? dt = null;
Type t = dt.GetType();

It was a NullReferenceException.

like image 2
Vadim Sentiaev Avatar answered Nov 02 '22 22:11

Vadim Sentiaev