I am trying to get a property names and values from an instance of an object. I need it to work for objects that contain nested objects where I can simple pass in the the parent instance.
For example, if I have:
public class ParentObject
{
public string ParentName { get; set; }
public NestedObject Nested { get; set; }
}
public class NestedObject
{
public string NestedName { get; set; }
}
// in main
var parent = new ParentObject();
parent.ParentName = "parent";
parent.Nested = new NestedObject { NestedName = "nested" };
PrintProperties(parent);
I have attempted a recursive method:
public static void PrintProperties(object obj)
{
var type = obj.GetType();
foreach (PropertyInfo p in type.GetProperties())
{
Console.WriteLine(p.Name + ":- " + p.GetValue(obj, null));
if (p.PropertyType.GetProperties().Count() > 0)
{
// what to pass in to recursive method
PrintProperties();
}
}
Console.ReadKey();
}
How do I determine that the property is then what is passed in to the PrintProperties?
You get the value already, try this: