I have an enum annotated with EnumMember
to facilitate JSON.NET serialization similar to the following:
[DataContract]
[JsonConverter(typeof(StringEnumConverter))]
public enum Status
{
[EnumMember(Value = "NOT_ADMITTED")]
NotAdmitted,
[EnumMember(Value = "ADMITTED")]
Admitted
}
Now, independent of the JSON.NET serialization I'd like to I'd like to convert instances of the enum to a string while abiding by the EnumMember
annotations in the data contract, e.g.:
aStatusInstance.ToString() == "NOT_ADMITTED"
.
Any suggestions? Thanks!
Update: My Solution
I modified the code in the accepted answer to create an extension method to retrieve the EnumMember Value:
public static string GetEnumMemberValue(this Enum enumValue)
{
var type = enumValue.GetType();
var info = type.GetField(enumValue.ToString());
var da = (EnumMemberAttribute[])(info.GetCustomAttributes(typeof(EnumMemberAttribute), false));
if (da.Length > 0)
return da[0].Value;
else
return string.Empty;
}