Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute inheritance on properties fails in C#

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?

like image 471
piggyBot Avatar asked Oct 24 '25 15:10

piggyBot


2 Answers

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);
like image 68
Pavel Anikhouski Avatar answered Oct 26 '25 03:10

Pavel Anikhouski


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.

like image 25
Eldar Avatar answered Oct 26 '25 04:10

Eldar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!