The other day I ran into the need to access a nested property on an object with the actual name and path to the property stored in a string variable. For example I had a mail object and wanted to access "From.DisplayName" which was stored in a string. If I was access just the from I could have used something like this:
using System.Reflection;
PropertyInfo[] pi = myObject.GetType().GetProperties();
foreach (PropertyInfo item in pi)
{
if (item.Name = "From")
{
object o = item.GetValue(myObject, null);
}
}
In this example myObject is the mail object and we first get the type of it, and then get an array of the properties for that type. Finally we find the From property and get the value for that property on our object.
Unfortunately this doesn't work for nested properties and I could not find a built in way to do it so I built a recursive function to handle getting the property for me and returning it. I then packaged it into a handy .Net 3.5 extension method. Let me know if you know of a built in method to get a nested property, otherwise feel free to using the extension method I put together, though it probably needs a bit of refactoring before you put it into production.
namespace Common.ExtensionMethods
{
public
static
class
TypeExtensionMethods
{
public
static
object GetNestedProperty(this
Type t, Object o, String Property)
{
object myObject = null;
PropertyInfo[] pi = t.GetProperties();
if (Property.IndexOf(".") != -1)
{
foreach (PropertyInfo item in pi)
{
if (item.Name == Property.Substring(0, Property.IndexOf(".")))
{
object tmpObj = item.GetValue(o, null);
myObject = tmpObj.GetType().GetNestedProperty(tmpObj, Property.Substring(Property.IndexOf(".") + 1));
}
}
}
else
{
foreach (PropertyInfo item in pi)
{
if (item.Name == Property)
{
myObject = item.GetValue(o, null);
}
}
}
return myObject;
}
}
}