Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a given Type is an Enum

Tags:

c#

enums

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.

like image 540
Bryan Migliorisi Avatar asked Nov 08 '11 02:11

Bryan Migliorisi


People also ask

How do you check if something is enum in Python?

To check if a value exists in an enum in Python: Use a list comprehension to get a list of all of the enum's values. Use the in operator to check if the value is present in the list. The in operator will return True if the value is in the list.

Is enum an object c#?

Enumeration (or enum) is a value data type in C#. It is mainly used to assign the names or string values to integral constants, that make a program easy to read and maintain.

Is nullable enum?

Enum types cannot be nullable.

What is enum value?

Enum. valueOf() method returns the enum constant of the specified enumtype with the specified name. The name must match exactly an identifier used to declare an enum constant in this type.


3 Answers

Use the IsEnum property:

if(objectType.IsEnum) {
    return true;
}
like image 118
Ry- Avatar answered Sep 27 '22 11:09

Ry-


Type.IsEnum is what your are looking for

like image 39
parapura rajkumar Avatar answered Sep 24 '22 11:09

parapura rajkumar


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;
    }
}
like image 37
Tom Avatar answered Sep 24 '22 11:09

Tom