148

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.

2
  • When you say "determine if objectType is an Enum", you basically want to check if the objectType is "MyEnum", rather than just any other enum. Is that correct? Nov 8, 2011 at 2:35
  • 1
    No I want to check if it is any Enum. @minitech's answer is what I am looking for. Nov 8, 2011 at 2:43

3 Answers 3

287

Use the IsEnum property:

if(objectType.IsEnum) {
    return true;
}
7
  • 79
    or just return objectType.IsEnum Nov 8, 2011 at 2:38
  • 7
    @AndrewWhitaker: I figured that since the method is called CanConvert, it will check for multiple different possible conversions, not just if it's an enum. Otherwise you may as well just use the IsEnum property itself.
    – Ry-
    Nov 8, 2011 at 2:40
  • 5
    @BryanMigliorisi: You're very welcome :) Make sure to always browse the IntelliSense, I've learned a lot from it.
    – Ry-
    Nov 8, 2011 at 2:45
  • 9
    @SergeyMetlov in PCL you can use objectType.GetTypeInfo().IsEnum Dec 23, 2015 at 13:22
  • how bout if (myObject is Enum) Jun 18, 2018 at 6:28
26

Type.IsEnum is what your are looking for

0
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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