2

This is MyEnum

public class CountryCodeAttr : EnumAttr
{
    public string Code { get; set; }
    public string Description { get; set; }
}

public enum CountryCode
{
    [CountryCodeAttr(Code = "Unknown", Description = "Unknown")]
    Unknown,
    [CountryCodeAttr(Code = "CH", Description = "Swiss", Currency="CHF")]
    CH
....

}

How can I, get the enum with a specific CountryCodeAttr? for example from attribute Currency?

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
  • I do not think this is a duplicate of the question listed. I believe he's asking for how to parse a currency value such as "CHF" to `CountryCode.CH` which is similar to https://stackoverflow.com/questions/1033260/how-can-i-get-an-enum-value-from-its-description but with a custom attribute. – TylerBrinkley Aug 29 '17 at 12:32

2 Answers2

1

You need to get it from the enum type:

CountryCode value = CountryCode.CH;
FieldInfo field = typeof(CountryCode).GetField(value.ToString());
var attr = field.GetCustomAttribute<CountryCodeAttr>();
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
0

There is another method to do this with generics:

public static T GetAttribute<T>(Enum enumValue) where T: Attribute
{
    T attribute;

    MemberInfo memberInfo = enumValue.GetType().GetMember(enumValue.ToString())
                                    .FirstOrDefault();

    if (memberInfo != null)
    {
        attribute = (T) memberInfo.GetCustomAttributes(typeof (T), false).FirstOrDefault();
        return attribute;
    }
    return null;
}
Feras Al Sous
  • 1,073
  • 1
  • 12
  • 23