Cranialsurge
Cranialsurge

Reputation: 95

Unable to extract a property value using reflection

I have two Types in this scenario - Type A and Type B. Type A is present in a higher layer and not where I'm implementing the code below and it has a property which is of Type B. Type B is defined in the layer(lower layer, think platform) that I'm working in. I'm trying to access Type A's property that is of Type B. If I understand correctly, via reflection I should be able to reflect over Type A and obtain this object(of Type B) as follows

Type targetTypeA = instanceOfTypeA.GetType();
PropertyInfo someProperty = instanceOfTypeA.GetProperty("PropertyName"); // again just to clarify, the type of this property is 'B' and present in this layer that I'm working in.
object propertyValue = someProperty.GetValue(targetTypeA, null);

The GetValue() method throws the following exception: System.Reflection.TargetException: 'Object does not match target type.'

Am I misinterpreting something here?

Upvotes: 1

Views: 242

Answers (1)

Cranialsurge
Cranialsurge

Reputation: 95

I was passing in 'Type' instead of the actual instance. The following code works:

Type targetTypeA = instanceOfTypeA.GetType();
PropertyInfo someProperty = instanceOfTypeA.GetProperty("PropertyName"); // again just to clarify, the type of this property is 'B' and present in this layer that I'm working in.
object propertyValue = someProperty.GetValue(instanceOfTypeA, null);

Upvotes: 1

Related Questions