Sergio Romero
Sergio Romero

Reputation: 6607

Get the type of an Object which is a property of another object

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.

Upvotes: 1

Views: 520

Answers (2)

DefLog
DefLog

Reputation: 1009

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.

Upvotes: 0

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422212

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

Upvotes: 2

Related Questions