There is a Nullable.GetUnderlyingType method that can help you in this case. You will probably eventually want to make your own utility method, because (I assume) you will use types with zero and non-empty value:
public static string GetTypeName(Type type) { var nullableType = Nullable.GetUnderlyingType(type); bool isNullableType = nullableType != null; if (isNullableType) return nullableType.Name; else return type.Name; }
Using:
Console.WriteLine(GetTypeName(typeof(DateTime?))); //outputs "DateTime" Console.WriteLine(GetTypeName(typeof(DateTime))); //outputs "DateTime"
EDIT: I suspect you can also use other mechanisms for this type, in which case you can change this a bit to get the base type or use the existing type if it is not null:
public static Type GetNullableUnderlyingTypeOrTypeIfNonNullable(this Type possiblyNullableType) { var nullableType = Nullable.GetUnderlyingType(possiblyNullableType); bool isNullableType = nullableType != null; if (isNullableType) return nullableType; else return possiblyNullableType; }
And this is a terrible name for the method, but I'm not smart enough to come up with one (I will be happy to change it if someone offers the best!)
Then, as an extension method, your use might look like this:
public static string GetTypeName(this Type type) { return type.GetNullableUnderlyingTypeOrTypeIfNonNullable().Name; }
or
typeof(DateTime?).GetNullableUnderlyingTypeOrTypeIfNonNullable().Name
source share