Can somebody explain to me why Value.GetType().GetCustomAttribute
returns null
? I have looked at ten different tutorials on how to get the attributes for an enumerated type member. No matter which GetCustomAttribute*
method I use, I get no custom attributes returned.
using System;
using System.ComponentModel;
using System.Reflection;
public enum Foo
{
[Bar(Name = "Bar")]
Baz,
}
[AttributeUsage(AttributeTargets.Field)]
public class BarAttribute : Attribute
{
public string Name;
}
public static class FooExtensions
{
public static string Name(this Foo Value)
{
return Value.GetType().GetCustomAttribute<BarAttribute>(true).Name;
}
}
Because the attribute you are trying to retrieve has not been applied to the type; it has been applied to the field.
Therefore, rather than calling GetCustomAttributes on the type object, you need to call it on the FieldInfo object. In other words, you would need to do something more like this:
typeof(Foo).GetField(value.ToString()).GetCustomAttributes...
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