typeof(DateTime?).Name == Nullable`1

Chad Carisch picture Chad Carisch · Dec 18, 2013 · Viewed 9.2k times · Source

Using Reflection in .Net typeof(DateTime?).Name returns "Nullable`1".

Is there any way to return the actual type as a string. (in this case "DateTime" or "System.DateTime")

I understand that DateTime? is Nullable<DateTime>. That's besides the point, I am just looking for the type of the nullable type.

Answer

Chris Sinclair picture Chris Sinclair · Dec 18, 2013

There's a Nullable.GetUnderlyingType method which can help you in this case. Likely you'll end up wanting to make your own utility method because (I'm assuming) you'll be using both nullable and non-nullable types:

public static string GetTypeName(Type type)
{
    var nullableType = Nullable.GetUnderlyingType(type);

    bool isNullableType = nullableType != null;

    if (isNullableType)
        return nullableType.Name;
    else
        return type.Name;
}

Usage:

Console.WriteLine(GetTypeName(typeof(DateTime?))); //outputs "DateTime"
Console.WriteLine(GetTypeName(typeof(DateTime))); //outputs "DateTime"

EDIT: I suspect you may also be using other mechanisms on the type, in which case you can slightly modify this to get the underlying type or use the existing type if it's non-nullable:

public static Type GetNullableUnderlyingTypeOrTypeIfNonNullable(this Type possiblyNullableType)
{
    var nullableType = Nullable.GetUnderlyingType(possiblyNullableType);

    bool isNullableType = nullableType != null;

    if (isNullableType)
        return nullableType;
    else
        return possiblyNullableType;
}

And that is a terrible name for a method, but I'm not clever enough to come up with one (I'll be happy to change it if someone suggests a better one!)

Then as an extension method, your usage might be like:

public static string GetTypeName(this Type type)
{
    return type.GetNullableUnderlyingTypeOrTypeIfNonNullable().Name;
}

or

typeof(DateTime?).GetNullableUnderlyingTypeOrTypeIfNonNullable().Name