get a property value of a complex type with reflection in c

You’re trying to get the value of a property as if it were a property of string – the first argument to GetValue needs to be the object you’re fetching the property from (oldEntity in this case). So you can get the department like this:

object department = oldEntity.GetType().GetProperty("Department").GetValue(oldEntity, null);

To get the Name property (which I hope is a property and not a public field) you need to do the same kind of thing again:

object name = department.GetType().GetProperty("Name").GetValue(department, null);

However, you could do this all somewhat more simply using dynamic typing:

dynamic entity = oldEntity;
string name = entity.Department.Name;

Note that there’s no compile-time checking for the Department or Name parts (or that the resulting type is string) but that’s the same as for the reflection-based code anyway. The dynamic typing would just do the reflection for you at execution time.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top