Inheritance and Custom Attributes
When implementing IDataErrorInfo support on Windsor Silverlight Example that uses aspect-like features of Castle DynamicProxy, I came across something interesting. I think we all have written a code to fetch the properties of an object using Reflection API, but this one got me going for some time before I noticed what the problem is.
Suppose on our cliche Customer object we search for the members decorated with a specific attribute. Here’s the Customer class:
public class Customer
And the following test, you assume, would pass:
and (not?) to your surprise, the test fails!
The reason is while our Age property is in fact decorated with Validation attribute, the GetCustomAttribute on PropertyInfo returns an empty array. But why does it return an empty array? You may think this has something to do with the fact that DynamicProxy creates an look alike object on top of our Customer class? But we have specified that we need to get inherited attributes (passing “true” value on GetCustomAttributes above).
Well, here’s the news which should have been apparent: passing true to
ICustomAttributeProvider.GetCustomAttributes method does NOT walk the type hierarchy.
The workaround, however, is pretty easy! Use Attribute class to do this and it will work just fine. The following test now passes: