views:

128

answers:

2

Hello,

For pupose of explaining let's say that I have a Company object which has an Address property of type Address. so it would be something like:

public class Company  
{  
    Address CompanyAddress;
}  

public class Address  
{
    int Number;
    string StreetName;  
}

Now I have a method that works with any kind of object type and I want to get a specific property from the received object, so I'm trying the following:

public string MyMethod(object myObject, string propertyName)
{
    Type objectType = myObject.GetType();
    object internalObject = objectType.GetProperty("Address");

    Type internalType = internalObject.GetType();
    PropertyInfo singleProperty = internalType.GetProperty("StreetName");

    return singleProperty.GetValue(internalObject, null).ToString();
}

The problem is that internalType is never Address but "System.Reflection.RuntimePropertyInfo" so singleProperty is always null;

How can I accomplish this?

Thank you.

+1  A: 

The problem with your code is that internalObject will be the PropertyInfo object returned by GetProperty method. You need to get the actual value of that property, hence the call to GetValue method.

public string MyMethod(object myObject, string propertyName) {
    Type objectType = myObject.GetType();
    object internalObject = objectType.GetProperty("Address").GetValue(myObject, null);

    Type internalType = internalObject.GetType();
    PropertyInfo singleProperty = internalType.GetProperty("StreetName");

    return singleProperty.GetValue(internalObject, null).ToString(); 
}
Mehrdad Afshari
This is perfect. Thank you so much !!!!
Sergio Romero
A: 

The internalObject is just a PropertyInfo object, just like singleProperty is.

You should use the same technique to extract the actual object:

    PropertyInfo addressProperty = objectType.GetProperty("Address");

    object interalObject = addressProperty.GetValue(myObject);

The rest is correct.

DefLog