Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetCustomAttribute returns null

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;
    }
}
like image 248
Tyler Crompton Avatar asked Jan 11 '13 19:01

Tyler Crompton


1 Answers

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...
like image 103
phoog Avatar answered Oct 09 '22 06:10

phoog