In my last post (http://blogs.msdn.com/weitao/archive/2009/05/28/override-properties-i.aspx) I revealed the truth behind property overriding. In today's article I will talk about how that impact the behavior of GetCustomAttributes.
In reflection a property is represented by a PropertyInfo object. There are two ways to get the custom attributes off of a PropertyInfo object:
The inherit boolean value, according to MSDN, "Specifies whether to search this member's inheritance chain to find the attributes". However, from the previous post we've already learned that there is no real inheritance chain for properties. The property "inheritance" is actually defined by the inheritance of the getter/setter methods.
The two GetCustomAttributes APIs are actually designed for different purposes.
So don't be surprised to find the two APIs return different results in the following code sample:
[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public sealed class MyAttribute : Attribute { }
public class Base
{
[MyAttribute]
public virtual int MyProperty { get { return 0; } }
}
public class Derived : Base
public override int MyProperty { get { return 42; } }
class Program
static void Main()
PropertyInfo p = typeof(Derived).GetProperty("MyProperty");
Console.WriteLine(p.IsDefined(typeof(MyAttribute), true));
Console.WriteLine(Attribute.IsDefined(p, typeof(MyAttribute), true));