Florian
Florian

Reputation: 4738

How to get nested properties

I want to retrieve a PropertyInfo, Here the code :

string propertyName="Text";
PropertyInfo pi = control.GetType().GetProperty(propertyName);

it works fine but if I want to retrieve nested properties, it returns null :

string propertyName="DisplayLayout.Override.RowSelectors";
PropertyInfo pi = control.GetType().GetProperty(propertyName);

Is there any way to get nested properties ?

Best Regards,

Florian

Edit : I have a new problem now, I want to get a property which is an array :

string propertyName="DisplayLayout.Bands[0].Columns";
PropertyInfo pi = control.GetType().GetProperty(propertyName)

Thank you

Upvotes: 7

Views: 13430

Answers (3)

Aren
Aren

Reputation: 55966

Yes:

public PropertyInfo GetProp(Type baseType, string propertyName)
{
    string[] parts = propertyName.Split('.');

    return (parts.Length > 1) 
        ? GetProp(baseType.GetProperty(parts[0]).PropertyType, parts.Skip(1).Aggregate((a,i) => a + "." + i)) 
        : baseType.GetProperty(propertyName);
}

Called:

PropertyInfo pi = GetProp(control.GetType(), "DisplayLayout.Override.RowSelectors");

Recursion for the win!

Upvotes: 16

Matteo Mosca
Matteo Mosca

Reputation: 7448

You can do it, but you have to do the "whole thing" for each level, meaning:

  • Get the property from your object type
  • Get the type of that property
  • Rinse and repeat :)

Upvotes: 0

Lucero
Lucero

Reputation: 60276

Just do the same again on the PropertyType you just got for the property (and repeat as often as you need):

PropertyInfo property = GetType().GetProperty(propertyName);
PropertyInfo nestedProperty = property.PropertyType.GetProperty(nestedPropertyName)

Upvotes: 3

Related Questions