I have the following property which has Inherited set to true.
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, Inherited = true)]
public class InheritedAttribute : Attribute { }
The class DerivedA contains a property which overrides BaseA's virtual property with a [InheritedAttribute] tag.
public class BaseA
{
[InheritedAttribute]
public virtual int prop { get; set; }
}
public class DerivedA : BaseA
{
public override int prop { get; set; }
}
Unfortunately, the attribute is not found on DerivedA.prop, thus the attribute has not been inherited to the child property.
public static void Main()
{
var propertyInfo = typeof(DerivedA).GetProperties()[0];
// propertyInfo.CustomAttributes is empty
// propertyInfo.GetCustomAttributes(true) is empty
}
If the attribute is placed on a method instead of a property, as seen in the example code on microsoft's website, the attribute is inherited as expected, and would be found in the methodInfo.CustomAttributes.
Is attribute inheritance simply not allowed on properties? Or am I missing something else entirely?
It happens because GetCustomAttributes method ignores the inherit parameter for the properties and events, according to MSDN specifications. Actually, your property has this attribute, you can check it by calling Attribute.GetCustomAttributes method, as recommended
var propertyInfo = typeof(DerivedA).GetProperties()[0];
var attributes = Attribute.GetCustomAttributes(propertyInfo);
Well that behavior is strange. But there is a work around like this:
var c = propertyInfo.GetCustomAttribute(typeof(InheritedAttribute), true);
Which is to specify directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With