Looping through classes, and child classes to retrieve properties and values in C#

Richard Whitehouse picture Richard Whitehouse · May 1, 2013 · Viewed 7.7k times · Source

I'm trying to loop through a class and it's child classes to get the values passed with it.

Here's my class:

public class MainClass
{
    bool IncludeAdvanced { get; set; }

    public ChildClass1 ChildClass1 { get; set; }
    public ChildClass2 ChildClass2 { get; set; }
}

Here's my code so far

GetProperties<MainClass>();

private void GetProperties<T>()
{
    Type classType = typeof(T);
    foreach (PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
    {
        WriteToLog(property.Name + ": " + property.PropertyType + ": " + property.MemberType);
        GetProperties<property>();
    }
}

Two questions:

  1. What do I pass to GetProperties, to pass the child class, for it to then loop through it's properties if it's a class?
  2. How do I get the value from the property item if it isn't a class?

Hopefully this all makes sense. If not, don't hesitate to ask and I'll try and clarify.

Thanks

Answer

Chris Sinclair picture Chris Sinclair · May 1, 2013

You can easily rewrite it to be recursive without generics:

private void GetProperties<T>()
{
    GetProperties(typeof(T));
}

private void GetProperties(Type classType)
{
    foreach (PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
    {
        WriteToLog(property.Name + ": " + property.PropertyType + ": " + property.MemberType);
        GetProperties(property.PropertyType);
    }
}

Not sure on your second question "how do I get the value from the property item if it isn't a class" (I'll edit/update when we figure that out)