I'm trying to loop through a class and it's child classes to get the values passed with it.
Here's my class:
public class MainClass
{
bool IncludeAdvanced { get; set; }
public ChildClass1 ChildClass1 { get; set; }
public ChildClass2 ChildClass2 { get; set; }
}
Here's my code so far
GetProperties<MainClass>();
private void GetProperties<T>()
{
Type classType = typeof(T);
foreach (PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
WriteToLog(property.Name + ": " + property.PropertyType + ": " + property.MemberType);
GetProperties<property>();
}
}
Two questions:
- What do I pass to GetProperties, to pass the child class, for it to then loop through it's properties if it's a class?
- How do I get the value from the property item if it isn't a class?
Hopefully this all makes sense. If not, don't hesitate to ask and I'll try and clarify.
Thanks
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:(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):
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.