Question

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.

Était-ce utile?

La solution

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

Autres conseils

As Pointed out by Patryk:

typeof(DateTime?).GetGenericArguments()[0].Name

Chris Sinclair code works but I rewrote it more concise.

public static Type GetNullableUnderlyingTypeIfNullable(Type possiblyNullableType)
    {
        return Nullable.GetUnderlyingType(possiblyNullableType) ?? possiblyNullableType;
    }

And then use it:

GetNullableUnderlyingTypeIfNullable(typeof(DateTime?)).Name
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top