Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Custom Attribute values for enums?

I have an enum where each member has a custom attribute applied to it. How can I retrieve the value stored in each attribute?

Right now I do this:

var attributes = typeof ( EffectType ).GetCustomAttributes ( false ); foreach ( object attribute in attributes ) {     GPUShaderAttribute attr = ( GPUShaderAttribute ) attribute;     if ( attr != null )         return attr.GPUShader; } return 0; 

Another issue is, if it's not found, what should I return? 0 is implcity convertible to any enum, right? That's why I returned that.

Forgot to mention, the above code returns 0 for every enum member.

like image 858
Joan Venge Avatar asked Feb 23 '11 22:02

Joan Venge


People also ask

How do I find enum attributes?

Enum. GetValues(typeof(FunkyAttributesEnum)); foreach (int value in values) Tuple. Value = Enum. GetName(typeof(FunkyAttributesEnum), value);

Can enums have attributes?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).

Can we assign value to enum?

Enum ValuesYou can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.


1 Answers

Try using a generic method

Attribute:

class DayAttribute : Attribute {     public string Name { get; private set; }      public DayAttribute(string name)     {         this.Name = name;     } } 

Enum:

enum Days {     [Day("Saturday")]     Sat,     [Day("Sunday")]     Sun,     [Day("Monday")]     Mon,      [Day("Tuesday")]     Tue,     [Day("Wednesday")]     Wed,     [Day("Thursday")]     Thu,      [Day("Friday")]     Fri } 

Generic method:

        public static TAttribute GetAttribute<TAttribute>(this Enum value)         where TAttribute : Attribute     {         var enumType = value.GetType();         var name = Enum.GetName(enumType, value);         return enumType.GetField(name).GetCustomAttributes(false).OfType<TAttribute>().SingleOrDefault();     } 

Invoke:

        static void Main(string[] args)     {         var day = Days.Mon;         Console.WriteLine(day.GetAttribute<DayAttribute>().Name);         Console.ReadLine();     } 

Result:

Monday

like image 128
George Kargakis Avatar answered Sep 19 '22 22:09

George Kargakis