Dustin Kofoed
Dustin Kofoed

Reputation: 549

How do you use reflection to get a sub property?

Let's see if I can explain what I'm trying to do...

Say I have an object, with a path to a property that looks like this:

Appointment.Person.Name

If I want to update the "Person" property, i could do something like this:

PropertyInfo subPropertyInfo = apptObject.GetType().GetProperty("Person");
subPropertyInfo.SetValue(apptObject, replacementValue, null);

But how would I update the Name Property for the root object?

Upvotes: 1

Views: 66

Answers (2)

James Thorpe
James Thorpe

Reputation: 32212

Get hold of the current value of Person, then update it in the same way as you currently are:

PropertyInfo subPropertyInfo = apptObject.GetType().GetProperty("Person");
Object p = subPropertyInfo.GetValue(apptObject);

PropertyInfo subSubPropertyInfo = p.GetType().GetProperty("Name");
subSubPropertyInfo.SetValue(p, replacementValue, null);

Upvotes: 2

Wyatt Earp
Wyatt Earp

Reputation: 1823

How about:

PropertyInfo subPropertyInfo = apptObject.Person.GetType().GetProperty("Name");
subPropertyInfo.SetValue(apptObject.Person, replacementValue, null);

Upvotes: 0

Related Questions