I'm trying to access various parts of a nested class structure using a arbitrary string.
Given the following (contrived) classes:
public class Person
{
public Address PersonsAddress { get; set; }
}
public class Adddress
{
public PhoneNumber HousePhone { get; set; }
}
public class PhoneNumber
{
public string Number { get; set; }
}
I'd like to be able to get the object at "PersonsAddress.HousePhone.Number"
from an instance of the Person
object.
Currently I'm doing some funky recursive lookup using reflection, but I'm hoping that some ninjas out there have some better ideas.
For reference, here is the (crappy) method I've developed:
private static object ObjectFromString(object basePoint, IEnumerable<string> pathToSearch)
{
var numberOfPaths = pathToSearch.Count();
if (numberOfPaths == 0)
return null;
var type = basePoint.GetType();
var properties = type.GetProperties();
var currentPath = pathToSearch.First();
var propertyInfo = properties.FirstOrDefault(prop => prop.Name == currentPath);
if (propertyInfo == null)
return null;
var property = propertyInfo.GetValue(basePoint, null);
if (numberOfPaths == 1)
return property;
return ObjectFromString(property, pathToSearch.Skip(1));
}