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?

1
  • 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 stackoverflow.com/questions/1033260/… but with a custom attribute. Commented Aug 29, 2017 at 12:32

2 Answers 2

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>();
Sign up to request clarification or add additional context in comments.

Comments

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.