I have the following program that loops through all properties of my variable:
class Program
{
static void Main(string[] args)
{
var person = new Person {Age = 30, Name = "Tony Montana", Mf = new Gender {Male = true,Female = false}};
var type = typeof(Person);
var properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("{0} = {1} : Value= {2}", property.Name, property.PropertyType, property.GetValue(person, null));
}
Console.Read();
}
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
public Gender Mf;
}
public class Gender
{
public bool Male;
public bool Female;
}
When I run this, I get the following output:
"Age = System.Int32 : Value= 30"
"Name = System.String : Value= Tony Montana"
I dont see my complex type person.Mf. How do i loop through my object person and get the type of person.Mf and the properties of person.Mf (i.e person.Mf.Male etc)? Thanks in advance
Mf is a field, not a property. Change it to:
Or, alternatively, use reflection to iterate through all of the public fields (but I think you’re better off just making it a property).