107

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?
0

5 Answers 5

205
public static bool IsNullableEnum(this Type t)
{
    Type u = Nullable.GetUnderlyingType(t);
    return u != null && u.IsEnum;
}
46

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;
}
4
  • 1
    I think I'd have done it Luke's way; less complex for the caller. Commented Apr 27, 2010 at 16:44
  • 2
    @Marc: I don't see how it makes any odds for the caller - but Luke's way is certainly nicer than mine.
    – Jon Skeet
    Commented Apr 27, 2010 at 16:45
  • Yeah definitely keep it for future reference
    – adrin
    Commented Apr 27, 2010 at 16:50
  • Yeah. I would have done "public static bool IsNullableEnum(object value) { if (value == null) { return true; } Type t = value.GetType(); return /* same as Jon's return */ ; }" because it may work with boxed types. And then overloaded with LukeH answer for better performance. Commented May 2, 2012 at 21:29
34

As from C# 6.0 the accepted answer can be refactored as

Nullable.GetUnderlyingType(t)?.IsEnum == true

The == true is needed to convert bool? to bool

1
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.

1

See http://msdn.microsoft.com/en-us/library/ms366789.aspx

Not the answer you're looking for? Browse other questions tagged or ask your own question.