Check if a given Type is an Enum

C#Enums

C# Problem Overview


I am writing a JsonConverter for Json.NET which should allow me to convert any enum's to a string value defined by a [Description] attribute.

For example:

public enum MyEnum {
    [Description("Sunday")] Sunday,
    [Description("Monday")] Monday,
    [Description("Tuesday")] Tuesday,
    [Description("Wednesday")] Wednesday,
    [Description("Thursday")] Thursday,
    [Description("Friday")] Friday,
    [Description("Saturday")] Saturday
}

I already have the code for supporting myEnum.Description() which will obviously return its string description.

In the JsonConverter implementation, there is this method:

    public override bool CanConvert(Type objectType)
    {

    }

I am trying to figure out how to determine if objectType is an Enum and return true so that the converter knows it can convert this object. Since I have many Enum's, I cannot explicitly check each one so I was hoping for a more generic way of accomplishing this.

C# Solutions


Solution 1 - C#

Use the IsEnum property:

if(objectType.IsEnum) {
    return true;
}

Solution 2 - C#

Type.IsEnum is what your are looking for

Solution 3 - C#

I completely misinterpreted the question by focusing too much on the [Description], so in case you ever want to check whether a particular enum has a [description] attribute or not ( in case json throws a fit when there is none ), this is one possible way to check for that:

public override bool CanConvert(Type objectType)
{
    FieldInfo[] fieldInfo = objectType.GetFields(BindingFlags.Public | BindingFlags.Static);

    if( fieldInfo.Length > 0 )
    {
        return ( fieldInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),false).Length > 0 );
    }
    else
    {
        return false;
    }
}

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
QuestionBryan MigliorisiView Question on Stackoverflow
Solution 1 - C#Ry-View Answer on Stackoverflow
Solution 2 - C#parapura rajkumarView Answer on Stackoverflow
Solution 3 - C#TomView Answer on Stackoverflow