Chris already answered the first part of your question, so I won't repeat that. For the second part, as soon as you have an instance of MainClass
, you can just use the (aptly named) PropertyInfo.GetValue method:
object value = property.GetValue(myInstance, null);
(If you use .NET 4.5, you can omit the second (null
) parameter. Earlier versions require it, though.)
In the end, your code could look like this (I shamelessly copied and extended Chris' version) (untested):
private void GetProperties<T>(T instance)
{
GetProperties(typeof(T), instance);
}
private void GetProperties(Type classType, object instance)
{
foreach (PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
WriteToLog(property.Name + ": " + property.PropertyType + ": " + property.MemberType);
object value = property.GetValue(instance, null);
if (value != null) {
WriteToLog(value.ToString());
GetProperties(property.PropertyType, value);
}
}
}
Note that this code will fail if any of your objects use indexed properties (C# indexers or properties with parameters in VB). In that case, GetValue would need to be provided with the appropriate index or parameter.