-3

How can I use the DescriptionAttibute to achieve the following with enums? Note the spaces in the enum values.

public enum PersonGender
    {
        Unknown = 0,
        Male = 1,
        Female = 2,
        Intersex = 3,
        Indeterminate = 3,
        Non Stated = 9,
        Inadequately Described = 9
    }
Charles
  • 50,943
  • 13
  • 104
  • 142
CJ7
  • 22,579
  • 65
  • 193
  • 321

1 Answers1

3

For example you can use like that:

It is our enum:

public enum MyEnum
{
   [Description("Description for Foo")]
   Foo,
   [Description("Description for Bar")]
   Bar
}

And our method for getting Attribute.

public static string GetDescription(this Enum value)
{
    Type type = value.GetType();
    string name = Enum.GetName(type, value);
    if (name != null)
    {
        FieldInfo field = type.GetField(name);
        if (field != null)
        {
             DescriptionAttribute attr =
                    Attribute.GetCustomAttribute(field,
                    typeof(DescriptionAttribute)) as DescriptionAttribute;
              if (attr != null)
              {
                   return attr.Description;
              }
        }
    }
    return null;
}

And you can get description:

  MyEnum x = MyEnum.Foo;
  string description = x.GetDescription();

Source

Community
  • 1
  • 1
Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98