Tyler Crompton
Tyler Crompton

Reputation: 12662

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

Upvotes: 5

Views: 17961

Answers (5)

Milad
Milad

Reputation: 479

I think you must rewrite FooExtension like this:

public static class FooExtensions
{
    public static string Name(this Foo Value)
    {
        string rv = string.Empty;
        FieldInfo fieldInfo = Value.GetType().GetField(Value.ToString());
        if (fieldInfo != null)
        {
            object[] customAttributes = fieldInfo.GetCustomAttributes(typeof (BarAttribute), true);
            if(customAttributes.Length>0 && customAttributes[0]!=null)
            {
                BarAttribute barAttribute = customAttributes[0] as BarAttribute;
                if (barAttribute != null)
                {
                    rv = barAttribute.Name;
                }
            }
        }

        return rv;
    }
}

Upvotes: 0

Tyler Crompton
Tyler Crompton

Reputation: 12662

I ended up rewriting it like this:

public static class FooExtensions
{
    public static string Name(this Foo Value)
    {
        var Type = Value.GetType();
        var Name = Enum.GetName(Type, Value);
        if (Name == null)
            return null;

        var Field = Type.GetField(Name);
        if (Field == null)
            return null;

        var Attr = Field.GetCustomAttribute<BarAttribute>();
        if (Attr == null)
            return null;

        return Attr.Name;
    }
}

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292465

phoog's explanation of the problem is correct. If you want an example of how to retrieve the attribute on an enum value, check out this answer.

Upvotes: 2

phoog
phoog

Reputation: 43046

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...

Upvotes: 18

Dhawalk
Dhawalk

Reputation: 1269

your attribute is at field level, whereas Value.GetType().GetCustomAttribute<BarAttribute>(true).Name would return attribute applied to enum Foo

Upvotes: 1

Related Questions