Consider the following scenario:
- The base class of the
BaseAttribute attribute has an AttributeUsageAttribute indicating that it is not inherited ( Inherited = False ). - The
DerivedAttribute derived attribute DerivedAttribute inherits from this base attribute class. - The base class of the
Base domain applies a derived attribute. - The
Derived domain class, which inherits from the base domain, is requested for its own attributes, including inherited attributes ( inherit: true ).
Here is the relevant code:
using System; using System.Linq; namespace ConsoleApplication26 { class Program { static void Main () { var attributes = typeof (Derived).GetCustomAttributes (true); foreach (var attribute in attributes) { Console.WriteLine ( "{0}: Inherited = {1}", attribute.GetType().Name, attribute.GetType().GetCustomAttributes (typeof (AttributeUsageAttribute), true).Cast<AttributeUsageAttribute>().Single().Inherited); } } } [AttributeUsage (AttributeTargets.All, Inherited = false)] public class BaseAttribute : Attribute { } public class DerivedAttribute : BaseAttribute { } [Derived] public class Base { } public class Derived : Base { } }
In this case, the GetCustomAttributes API returns an instance of the DerivedAttribute class. I would expect it to not return this instance, because http://msdn.microsoft.com/en-us/library/system.attributeusageattribute.aspx says that AttributeUsageAttribute itself is inherited.
Now, is this a mistake, or can it be expected / documented somewhere?
Note (2013-02-20): Experiments show that the AttributeTargets part of the BaseAttribute class BaseAttribute indeed inherited by the DerivedAttribute class. For example, when I change valid targets to BaseAttribute to AttributeTargets.Method , the C # compiler will not let me apply DerivedAttribute to the class. Therefore, it does not make sense that the Inherited = False not inherited by DerivedAttribute , and therefore I tend to think about an error in the implementation of GetCustomAttributes .
source share