Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum.ToString() that abides EnumMemberAnnotation

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;
    }
like image 584
HolySamosa Avatar asked Sep 18 '12 00:09

HolySamosa


1 Answers

I would use the Description Attribute and decorate the enum with the same value as the EnumMember:

    [DataContract]
    [JsonConverter(typeof(StringEnumConverter))]
    public enum Status
    {
        [EnumMember(Value = "NOT_ADMITTED")]
        [Description("NOT_ADMITTED")]
        NotAdmitted,
        [EnumMember(Value = "ADMITTED")]
        [Description("ADMITTED")]
        Admitted
    }

You can use this code snippet to parse it. This is written as an extension of the Enum class:

    public static string GetDescription(this Enum enumValue)
    {
        Type type = enumValue.GetType();
        FieldInfo info = type.GetField(enumValue.ToString());
        DescriptionAttribute[] da = (DescriptionAttribute[])(info.GetCustomAttributes(typeof(DescriptionAttribute), false));

        if (da.Length > 0)
            return da[0].Description;
        else
            return string.Empty; 
    }

You can then compare it with the following:

    aStatusInstance.GetDescription() == "NOT_ADMITTED"
like image 159
scottmgerstl Avatar answered Nov 09 '22 05:11

scottmgerstl