user9248102
user9248102

Reputation: 299

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.

Upvotes: 2

Views: 2070

Answers (3)

Diego Rafael Souza
Diego Rafael Souza

Reputation: 5313

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
    }
}

Upvotes: 8

Wearwolf
Wearwolf

Reputation: 190

GetProperties() gets you PropertyInfo objects which tell you information about the properties of the object. You need to use GetValue to actually get the values of those properties. From there you can repeat the process to get the values of that object's properties.

foreach (var v in test.GetType().GetProperties())
{
    var propertyValue = v.GetValue(test);
    foreach (var p in propertyValue.GetType().GetProperties())
    {
        var subPropertyValue = p.GetValue(propertyValue);
        Console.WriteLine("{0} = {1}", p.Name, subPropertyValue);
    }
}

After editing the value use SetValue to persist it back to the object.

Upvotes: 0

Eric Lippert
Eric Lippert

Reputation: 659964

The type returned by v.GetType() is that of PropertyInfo, because v is a property info. You don't want the properties of the PropertyInfo type, you want the properties of the type itself.

Use v.PropertyType, not v.GetType().

Upvotes: 7

Related Questions