Checking if Type instance is a nullable enum in C#

C#EnumsNullable

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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;
}

Solution 3 - C#

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

Solution 4 - C#

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.

Solution 5 - C#

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionadrinView Question on Stackoverflow
Solution 1 - C#LukeHView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#BigjimView Answer on Stackoverflow
Solution 4 - C#Bryan WattsView Answer on Stackoverflow
Solution 5 - C#Daniel RenshawView Answer on Stackoverflow