Codeine .Net RSS 2.0
# Sunday, 25 November 2007

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;

 

}

}

}

Sunday, 25 November 2007 10:03:26 (Central Standard Time, UTC-06:00)  #    Comments [1] - Trackback - Save to del.icio.us - Digg This! - Follow me on Twitter
Development | Extension Methods

Navigation
Archive
<2007 November>
SunMonTueWedThuFriSat
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2024
David A. Osborn
Sign In
Statistics
Total Posts: 70
This Year: 0
This Month: 0
This Week: 0
Comments: 33
Themes
Pick a theme:
All Content © 2024, David A. Osborn
DasBlog theme 'Business' created by Christoph De Baene (delarou)