How can I differentiate if an object is of type DateTime or NullableDateTime> (DateTime?)?
I understand why the following code does not work, but can you help me with a solution that does?
public void Test()
{
DateTime? dateTime1 = new DateTime(2020, 1, 1);
DateTime dateTime2 = new DateTime(2020, 1, 1);
DoSomething(dateTime1);
DoSomething(dateTime2);
}
public void DoSomething(object value)
{
if (value is DateTime?)
{
//Do something
}
if (value is DateTime)
{
//Do something else
}
}
It is not possible due to how nullabale value types are boxed in C#:
- If HasValue returns false, the null reference is produced.
- If HasValue returns true, the corresponding value of the underlying value type T is boxed, not the instance of Nullable.
So basically there is no such thing as boxed nullable value types.
Not sure what your actual case it, but in the provided scenario you can make your method generic and use Nullable.GetUnderlyingType
:
public void DoSomething<T>(T value)
{
var typeOfT = typeof(T);
if(Nullable.GetUnderlyingType(typeOfT) == typeof(DateTime))
{
Console.WriteLine("nullable dt");
}
else if(typeOfT == typeof(DateTime))
{
Console.WriteLine("dt");
}
}
DoSomething(dateTime1); // prints "nullable dt"
DoSomething(dateTime2); // prints "dt"