Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 933
Chad Carisch Avatar asked Dec 18 '13 13:12

Chad Carisch


People also ask

How do you check if a nullable is null?

To check if PropertyType is nullable, we can use `System. Nullable. GetUnderlyingType(Type nullableType)`, see example below and reference here.


3 Answers

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
like image 194
Chris Sinclair Avatar answered Oct 21 '22 07:10

Chris Sinclair


As Pointed out by Patryk:

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

like image 42
Chad Carisch Avatar answered Oct 21 '22 06:10

Chad Carisch


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
like image 5
Domenico Avatar answered Oct 21 '22 05:10

Domenico