Skip to content

PropertyInfo.GetCustomAttributes() Doesn’t Return Inherited Attributes

Here’s a problem I ran into today. If you have an attribute on the property of a base class; are you able to read it via PropertyInfo.GetCustomAttributes on the properties of a subclass.

Here’s where it helps to read the fine print. PropertyInfo.GetCustomAttributes takes a parameter for ‘inherit’ – yet the reference for PropertyInfo contains some important details:

Calling ICustomAttributeProvider.GetCustomAttributes on PropertyInfo when the inherit parameter of GetCustomAttributes is true does not walk the type hierarchy. Use System.Attribute to inherit custom attributes.

The code to read the attributes ended up looking like this:

foreach (PropertyInfo property in type.GetProperties())
    // not this one -> property.GetCustomAttributes(true);
    Attribute[] attributes = Attribute.GetCustomAttributes(property);

Post a Comment

Your email is never published nor shared. Required fields are marked *