Tarion
Tarion

Reputation: 17134

Different behavior while getting the attributes of overridden properties?

using System;

class Program
{
    static void Main()
    {
        var p = typeof(MyClass2).GetProperty("Value");
        var a = Attribute.GetCustomAttribute(p, typeof(ObsoleteAttribute), true);
        Console.WriteLine(a != null);
    }
}

public class MyClass
{
    [CommandProperty()]
    public virtual string Value { get; set; }
}

public class MyClass2 : MyClass
{
    public override string Value { get; set; }
}

[AttributeUsage( AttributeTargets.Property, Inherited = true)]
public class CommandPropertyAttribute : Attribute
{
/* ... */
}

PropertyInfo prop = ***The PropertyInfo of MyClass2.Value***;
object[] attrs = prop.GetCustomAttributes( typeofCPA, true );
Attribute at =Attribute.GetCustomAttribute(prop, typeofCPA, true);
if (attrs.Length == 0 && at != null)
{
    // Yes this happens.        
}

Why do I get no result from the first GetCustomAttributes call?

Upvotes: 0

Views: 190

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 180917

The documentation for MemberInfo.GetCustomAttributes (inherited to PropertyInfo) states;

This method ignores the inherit parameter for properties and events. To search the inheritance chain for attributes on properties and events, use the appropriate overloads of the Attribute.GetCustomAttributes method.

In other words, (wrong) behavior by design.

Upvotes: 2

Related Questions