Check if a given Type is an Enum
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.
Solution 1:
Use the IsEnum
property:
if(objectType.IsEnum) {
return true;
}
Solution 2:
Type.IsEnum is what your are looking for
Solution 3:
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;
}
}