views:

65

answers:

2

Hi everybody. I'm trying to use reflection for some reason and I got into this problem.

class Service
{
    public int ID {get; set;}
    .
    .
    .
}

class CustomService
{
    public Service srv {get; set;}
    .
    .
    .
}

//main code

Type type = Type.GetType(typeof(CustomService).ToString());
PropertyInfo pinf = type.GetProperty("Service.ID"); // returns null

My problem is that I want to get a propery inside another property of the main object. Is there a simple way to this goal?

Thanks in Advance.

+5  A: 

You will need to first obtain a reference to the srv property and then the ID:

class Program
{
    class Service 
    { 
        public int ID { get; set; } 
    }

    class CustomService 
    { 
        public Service srv { get; set; } 
    }

    static void Main(string[] args)
    {
        var serviceProp = typeof(CustomService).GetProperty("srv");
        var idProp = serviceProp.PropertyType.GetProperty("ID");

        var service = new CustomService
        {
            srv = new Service { ID = 5 }
        };

        var srvValue = serviceProp.GetValue(service, null);
        var idValue = (int)idProp.GetValue(srvValue, null);
        Console.WriteLine(idValue);
    }
}
Darin Dimitrov
+1  A: 

You have to reflect on the custom service and find the property value. After that you have to reflect on that property and find its value. Like so:

var customService = new CustomService();  
customService.srv = new Service() { ID = 409 };  
var srvProperty = customService.GetType().GetProperty("srv");  
var srvValue = srvProperty.GetValue(customService, null);  
var id = srvValue.GetType().GetProperty("ID").GetValue(srvValue, null);  
Console.WriteLine(id);
sduplooy