Getting Nested Object Property Value Using Reflection
This will work for unlimited number of nested property.
public object GetPropertyValue(object obj, string propertyName)
{
var _propertyNames = propertyName.Split('.');
for (var i = 0; i < _propertyNames.Length; i++)
{
if (obj != null)
{
var _propertyInfo = obj.GetType().GetProperty(_propertyNames[i]);
if (_propertyInfo != null)
obj = _propertyInfo.GetValue(obj);
else
obj = null;
}
}
return obj;
}
Usage:
GetPropertyValue(_employee, "Firstname");
GetPropertyValue(_employee, "Address.State");
GetPropertyValue(_employee, "Address.Country.Name");
public object GetPropertyValue(object obj, string propertyName)
{
foreach (var prop in propertyName.Split('.').Select(s => obj.GetType().GetProperty(s)))
obj = prop.GetValue(obj, null);
return obj;
}
Thanks, I came here looking for an answer to the same problem. I ended up modifying your original method to support nested properties. This should be more robust than having to do nested method calls which could end up being cumbersome for more than 2 nested levels.