Getting Nested Object Property Value Using Reflection
        Posted  
        
            by Kumar
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Kumar
        
        
        
        Published on 2010-03-29T01:05:37Z
        Indexed on 
            2010/03/29
            1:13 UTC
        
        
        Read the original article
        Hit count: 736
        
I have the following two classes:
public class Address
{
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}
public class Employee
{
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public Address EmployeeAddress { get; set; }
}
I have an instance of the employee class as follows:
    var emp1Address = new Address();
    emp1Address.AddressLine1 = "Microsoft Corporation";
    emp1Address.AddressLine2 = "One Microsoft Way";
    emp1Address.City = "Redmond";
    emp1Address.State = "WA";
    emp1Address.Zip = "98052-6399";
    var emp1 = new Employee();
    emp1.FirstName = "Bill";
    emp1.LastName = "Gates";
    emp1.EmployeeAddress = emp1Address;
I have a method which gets the property value based on the property name as follows:
public object GetPropertyValue(object obj ,string propertyName)
{
    var objType = obj.GetType();
    var prop = objType.GetProperty(propertyName);
    return prop.GetValue(obj, null);
}
The above method works fine for calls like GetPropertyValue(emp1, "FirstName") but if I try GetPropertyValue(emp1, "Address.AddressLine1") it throws an exception because objType.GetProperty(propertyName); is not able to locate the nested object property value. Is there a way to fix this?
© Stack Overflow or respective owner