« Home | Silverlight Animated Optical Illusion » | ObjectDataSource DateTime, and Locale » | How Does OpenID Work? » | Facebook dev, IIS 5.1, and error 405 » | Creating Your Own Dev SSL Cert for IIS » | Moving from ASP.NET 1.1 to 2.0 » | Link Drop VI » | Silverlight createFromXaml Bug » | C# command line parser? » | Firefox extension: CookiePie » 

Wednesday, March 26, 2008 

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);
}

Cheers, was bashing my head against the same issue.

Post a Comment