2

I have the following code:

public interface IFoo
{
    [DisplayName("test")]
    string Name { get; set; }
}

public class Foo : IFoo
{
    public string Name { get; set; }
}

Using reflection I need to get the attribute from the property Name. However I don't know if the Type I will receive is an interface or the concrete class.

If I try to do a prop.GetCustomAttributes(true) on the concrete class it doesn't return the attribute I've set on the interface. I would like it to return in this case.

Is there a method to get attributes defined on the concrete class and the interface as well? Or how could I handle this?

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • 1
    Check [attribute inheritance](http://stackoverflow.com/questions/1240960/how-does-inheritance-work-for-attributes) and how they are [handled on the property level](http://stackoverflow.com/questions/2520035/inheritance-of-custom-attributes-on-abstract-properties). – Michael Dec 11 '14 at 12:01

2 Answers2

4

There is no built-in method to do this, but you can write one:

public static T GetAttribute<T>(this PropertyInfo pi) where T : Attribute
{
    var attr = pi.GetCustomAttribute<T>();
    if (attr != null) return attr;

    var type = pi.DeclaringType;
    var interfaces = type.GetInterfaces();

    foreach(var i in interfaces)
    {
        var p = i.GetProperties().FirstOrDefault(x => Attribute.IsDefined(x,typeof(T)));           
        if (p != null)
            return p.GetCustomAttribute<T>();
    }
    return null;
}

Usage:

var f = new Foo();
var prop = f.GetType().GetProperty("Name");
var attr = prop.GetAttribute<DisplayNameAttribute>();
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
2

The class doesn't inherit the attributes from the interface. So you'll have to call Type.GetInterfaces() to find out the interfaces, and try to find the attributes on that.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272