Search code examples
c#reflectionsystem.reflection

Get properties of properties of a class


I want to get the properties of the properties of a class.

What I have right now:

foreach (var v in test.GetType().GetProperties())
{
    foreach (var p in v.GetType().GetProperties())
    {
    }
}

The first foreach loop works fine and gets the properties of the class variable test. However, in the second loop, I get output such as MemberType, ReflectedType, Module etc.. not actual properties.

My goal is to get the properties of the properties of a class and then edit their value (truncate them using another function).

Thanks.


Solution

  • On the second loop GetType() returns a PropertyInfo object. You have to get the propertyType of v as v.PropertyType.GetProperties() to achieve what you want.

    So, the code should be:

    foreach (var v in test.GetType().GetProperties())
    {
        foreach (var p in v.PropertyType.GetProperties())
        {
            // Stuff
        }
    }