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.
The problem with your code is that
internalObjectwill be thePropertyInfoobject returned byGetPropertymethod. You need to get the actual value of that property, hence the call toGetValuemethod.