Search code examples
c#system.reflectionpropertyinfo

Get the propertyInfo by the path to it?


I want to get the propertyInfo by the path that look like this:

string path = "window.position.x";

Here an example:

PropertyInfo p = typeof(WindowManager).GetProperty(path);

the WindowManager has a property called "window", which has a property called "position" which again has the property "x".

Is there some way to achieve this? Unfortunatelly GetProperty doesn't work with such a path.


Solution

  • You can split your path and iterate through metadata. Try this code:

    var type = typeof(WindowManager);
    PropertyInfo property;
    foreach (var prop in path.Split('.'))
    {
        property = type.GetProperty(prop);
        if (property == null)
        {
            // log error
            break;
        }
        type = property.PropertyType;
    }
    
    // now property is x
    

    Note that you should check property on each iteration to make sure your path is valid

    Demo