3

Possible Duplicate:
Getting attributes of Enum’s value

This is my class:

[AttributeUsage(AttributeTargets.Field)]
public sealed class LabelAttribute : Attribute
{

    public LabelAttribute(String labelName)
    {
        Name = labelName;
    }

    public String Name { get; set; }

}

and I want to get the fields of the attributes:

public enum ECategory
{
    [Label("Safe")]
    Safe,
    [Label("LetterDepositBox")]
    LetterDepositBox,
    [Label("SavingsBookBox")]
    SavingsBookBox,
}
Community
  • 1
  • 1

3 Answers3

2

Read the ECategory.Safe Label attribute value:

var type = typeof(ECategory);
var info = type.GetMember(ECategory.Safe.ToString());
var attributes = info[0].GetCustomAttributes(typeof(LabelAttribute), false);
var label = ((LabelAttribute)attributes[0]).Name;
Stefan P.
  • 9,489
  • 6
  • 29
  • 43
0

You can Create an Extension:

public static class CustomExtensions
  {
    public static string GetLabel(this ECategory value)
    {
      Type type = value.GetType();
      string name = Enum.GetName(type, value);
      if (name != null)
      {
        FieldInfo field = type.GetField(name);
        if (field != null)
        {
          LabelAttribute attr = Attribute.GetCustomAttribute(field, typeof(LabelAttribute )) as LabelAttribute ;
          if (attr != null)
          {
            return attr.Name;
          }
        }
      }
      return null;
    }
  }

Then you can do:

var category = ECategory.Safe;    
var labelValue = category.GetLabel();
default
  • 11,485
  • 9
  • 66
  • 102
SBurris
  • 7,378
  • 5
  • 28
  • 36
0
var fieldsMap = typeof(ECategory).GetFields()
    .Where(fi => fi.GetCustomAttributes().Any(a => a is LabelAttribute))
    .Select(fi => new
    {
        Value = (ECategory)fi.GetValue(null),
        Label = fi.GetCustomAttributes(typeof(LabelAttribute), false)
                .Cast<LabelAttribute>()
                .Fist().Name
    })
    .ToDictionary(f => f.Value, f => f.Label);

Afterwards you can retrieve the label for each value like this:

var label = fieldsMap[ECategory.Safe];
RePierre
  • 9,358
  • 2
  • 20
  • 37