   [.net] Get an object by name
  I am trying to figure out a very generic way to save some data from an app I'm working on.  I'd like to be able to set a property of an object, only using it's name (as a string), and then save the object that it belongs to.  Below is some code to show what I'm trying to achieve.  In the Save() function of Foo I have some comments that say/show what I'd like to get working.public class Person{    public Address HomeAddress { get; set; }    public Person() { HomeAddress = new Address(); }}public class Address{    public string Street { get; set; }    public string Street2 { get; set; }    public Address() { }    public void Save() { /* Do Save stuff */ }}public class Foo{    public Person person { get; set; }    public Foo()    {   person = new Person();   Save("123 Test Street", "Street");    }    public void Save(string value, string propertyName)    {   PropertyInfo[] propInfos = person.GetType().GetProperties();   PropertyInfo info = GetProperty(propInfos, propertyName);   // info is returned with the information for the Street property in HomeAddress.   // Is there a way to set HomeAddress.Street = value, and then call HomeAddress.Save() using Reflection?    }    private PropertyInfo GetProperty(PropertyInfo[] pis, string propertyName)    {   foreach (PropertyInfo pi in pis)   {  if (pi.Name == propertyName)  { return pi;  }  else  { if (pi.PropertyType.FullName.StartsWith("MyLibraryName")) {PropertyInfo p2 = GetProperty(pi.PropertyType.GetProperties(), propertyName);if (p2 != null)    return p2; }  }   }   return null;    }}
  Look up Dictionary.   ;PropertyInfo.SetValue() will do just that.  You need to have a reference to the target object, whose Property you wish to change.   ;  I actually got it figured out.  Here is the code for reference.  What I ended up doing was passing the full path from the base object to the property (HomeAddress.Street instead of just Street).  This will also help with issues where there is more than one object with the same property name.public Foo()    {   person = new Person();   // Both of these need to work, even though the properties belong to 2 different objects   MyGenericSave("123 Test Street", "HomeAddress.Street");   MyGenericSave("John Doe", "Name");    }    public void MyGenericSave(string value, string propertyName)    {   PropertyInfo pi = null;   object currentObject = person;   object lastObject = person;   string[] splitter = new string[] { "." };   string[] propNames = propertyName.Split(splitter, StringSplitOptions.None);   string actualPropertyName = propNames[propNames.Length - 1];   for (int i = 0; i < propNames.Length; i++)   {  pi = currentObject.GetType().GetProperty(propNames);  currentObject = pi.GetValue(currentObject, null);  if (currentObject != null)  { lastObject = currentObject;  }   }   pi.SetValue(lastObject, value, null);   MethodInfo mi = lastObject.GetType().GetMethod("Save");   mi.Invoke(lastObject, null);    }