Why is GetType() returning DateTime type for Nullable<DateTime>
Solution 1
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()
Solution 2
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
}
}
Solution 3
Because if you write something like this:
DateTime? dt = null; Type t = dt.GetType();
It was a NullReferenceException.
veljkoz
Programming usually in .NET, with SQL Server as backend, but always open to new solutions. Interested in software architecture in general
Updated on June 05, 2022Comments
-
veljkoz almost 2 years
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?
orNullable<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? -
Cipi over 13 yearsGave back +1... only because he is a new user here.