Enum.ToString() that abides EnumMemberAnnotation
Asked Answered
T

1

10

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;
    }
Turnover answered 18/9, 2012 at 0:1 Comment(2)
This is what you need -> #797107Bevbevan
Great idea with the adaptation.Trabzon
T
5

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"
Trabzon answered 18/9, 2012 at 1:30 Comment(1)
Thanks! I think I'll go with this but modify your extension method to read from the EnumMember attribute.Turnover

© 2022 - 2024 — McMap. All rights reserved.