Ok, I’m trying to use reflection to iterate through a class to get all properties and values of that class and sub classes. The problem I am running into is getting the values of a class that is a subclass of the object I’m working with. For Example. I want to get the ClassRoom properties for the Teacher object in the example below.
Another issue I’m having is how to determine when I get to a containable property such as the List of Students so I can then have it iterate through the list.
ex:
public class Teacher
{
public int ID {get;set;}
public string FullName {get;set;}
public ClassRoom HomeRoom {get;set;}
public List<Student> Students {get;set;}
}
public class ClassRoom
{
public int ID {get;set;}
public string RoomNumber {get;set;}
}
public class Student
{
public int ID {get;set;}
public string FullName {get;set;}
}
private void LoadTeacher()
{
Teacher thisTeacher = Session["Teacher"] as Teacher;
Type type = thisTeacher.GetType();
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string))
{
Type headerType = prop.PropertyType;
PropertyInfo[] headerProps = headerType.GetProperties();
//Instantiate an object of the headerType
object headerObj = Activator.CreateInstance(headerType);
foreach (PropertyInfo childProp in headerProps)
{
if (!childProp.PropertyType.IsClass || childProp.PropertyType == typeof(string))
{
//This object always get loaded with default values, Why?
object value = childProp.GetValue(headerObj, null);
}
}
}
}
}
Output