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.
Enum. GetValues(typeof(FunkyAttributesEnum)); foreach (int value in values) Tuple. Value = Enum. GetName(typeof(FunkyAttributesEnum), value);
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With