A Bug with Reflection and Inheritance
June 27th, 2007Last week a bug in the String object was found. It was apparently due to a compiler optimization which will not be fixed for a while. But we have come this far without discovering it, so we can wait a little longer.
The last few days I have been trying to fix a bug that was making absolutely no sense to me. It turns out my problem is another known bug in the .NET framework. I am using reflection to automatically bind data values to objects which inherit from a base class. The base class actually does all of the work while the inheriting classes define properties which line up with the data values from the database. I confirm that the name and type of the property is the same as the data value but when the SetValue method on the PropertyInfo object was called it threw a TargetException.
TargetException: Object does not match target type.
It was not the easiest bug to fix. I searched around for a while before I came across an older post from Ayende called Polymophic DataBinding Solutions that goes into a related problem. It seems reflection has a problem with inheritance which I suspected but did not believe was likely until I found Ayende's post.
Fixing it once I knew the reason it was broken was another matter which was fortunately not all that hard. My base class is called DomainObject and I decided to get past the reflection bug using generics. It was really just a shot in the dark because I do not know what is causing the reflection bug but once I made the changes and ran my unit tests everything passed successfully.
In the code below you can see the base class named DomainObject and one of the inheriting classes named Location. It may look funny and even redundant, but it works.