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.
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.
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.
Enum types cannot be nullable.
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.
Use the IsEnum
property:
if(objectType.IsEnum) {
return true;
}
Type.IsEnum is what your are looking for
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With