102

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?
adrin
  • 3,738
  • 8
  • 40
  • 60

5 Answers5

199
public static bool IsNullableEnum(this Type t)
{
    Type u = Nullable.GetUnderlyingType(t);
    return (u != null) && u.IsEnum;
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
LukeH
  • 263,068
  • 57
  • 365
  • 409
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;
}
Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    I think I'd have done it Luke's way; less complex for the caller. – Marc Gravell Apr 27 '10 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 Apr 27 '10 at 16:45
  • Yeah definitely keep it for future reference – adrin Apr 27 '10 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. – TamusJRoyce May 02 '12 at 21:29
30

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

Bigjim
  • 2,145
  • 19
  • 19
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.

Bryan Watts
  • 44,911
  • 16
  • 83
  • 88
1

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

Daniel Renshaw
  • 33,729
  • 8
  • 75
  • 94