-2
public class A
{
   public B b { get; set;}
}
public class B
{
   public C c { get; set;}
}
public class C
{
   public string Name { get; set; }
}

I need to reach the value of C.Name dynamically using reflection. With my limited imagination I can only reach the second layer with the code below

 Type type = a.GetType();
 PropertyInfo[] properties = type.GetProperties();
 foreach (PropertyInfo property in properties)
 {
     var subObject = type.GetProperty(property.Name).GetValue(a); // this is b
     foreach (var subProperty in subObject.GetType().GetProperties())
     {
          var propertyValue = subProperty.GetValue(subObject);
     }
 }

What should be my next step?

  • 1
    Recursion is your friend in this case. [help-with-creating-a-recursive-function-c-sharp](https://stackoverflow.com/questions/1313969/help-with-creating-a-recursive-function-c-sharp) – Ryan Wilson Apr 16 '21 at 19:59

2 Answers2

0
A instA = new A { b = new B { c = new C { Name = "Bob" } }  };

Type typeA = instA.GetType();
PropertyInfo propB = typeA.GetProperty("b");
Object instB = propB.GetValue(instA);

Type typeB = instB.GetType();
PropertyInfo propC = typeB.GetProperty("c");
Object instC = propC.GetValue(instB);

Console.WriteLine(((C)instC).Name);

Result:

Bob
Nicholas Hunter
  • 1,791
  • 1
  • 11
  • 14
0

Using an extension method for Reflection down property paths:

public static class ObjectExt {
    public static object GetPropertyPathValue(this object curObject, string propsPath) {
        foreach (var propName in propsPath.Split('.'))
            curObject = curObject.GetType().GetProperty(propName).GetValue(curObject);

        return curObject;
    }    
}

You can access the property using a string path:

var name = a.GetPropertyPathValue("b.c.Name");
NetMage
  • 26,163
  • 3
  • 34
  • 55