tags:

views:

299

answers:

4

How do i check if a Type is a nullable enum in C# something like

Type t = GetMyType();
bool isEnum = t.IsEnum; //Type member
bool isNullableEnum = t.IsNullableEnum(); How to implement this extension method?
+10  A: 

EDIT: I'm going to leave this answer up as it will work, and it demonstrates a few calls that readers may not otherwise know about. However, Luke's answer is definitely nicer - go upvote it :)

You can do:

public static bool IsNullableEnum(this Type t)
{
    return t.IsGenericType &&
           t.GetGenericTypeDefinition() == typeof(Nullable<>) &&
           t.GetGenericArguments()[0].IsEnum;
}
Jon Skeet
I think I'd have done it Luke's way; less complex for the caller.
Marc Gravell
@Marc: I don't see how it makes any odds for the *caller* - but Luke's way is certainly nicer than mine.
Jon Skeet
Yeah definitely keep it for future reference
adrin
A: 
public static bool IsNullable(this Type type)
{
    return type.IsClass
        || (type.IsGeneric && type.GetGenericTypeDefinition == typeof(Nullable<>));
}

I left out the IsEnum check you already made, as that makes this method more general.

Bryan Watts
+13  A: 
public static bool IsNullableEnum(this Type t)
{
    Type u = Nullable.GetUnderlyingType(t);
    return (u != null) && u.IsEnum;
}
LukeH