0

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.

1
  • 2
    Why Type.GetType(typeof(CustomService).ToString()) instead of typeof(CustomService)? Commented Mar 3, 2010 at 8:04

2 Answers 2

5

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.