Search code examples
c#.netsystem.reflection

System.Reflection - How can I get the PropertyInfo of the sublevel Types?


I have got three classes as follows:

public class TestA
{
    public string Str1 { get; set; }
    public string Str2 { get; set; }
    public List<TestB> LstTestBs { get; set; }
    public TestC ObjTestC { get; set; }
}

public class TestB
{
    public string Str3 { get; set; }
    public string Str4 { get; set; }
}

public class TestC
{
    public string Str5 { get; set; }
}

I have tried:

var prop = typeof (TestA).GetProperties();

But, it is giving only the PropertyInfo for the four members inside TestA. I need to get the PropertyInfo for all the members in the TestA, TestB and TestC classes.

Please help... Thanks in advance, San


Solution

  • Thanks for the help everyone. I have got the answer.

            var prop = typeof (TestA).GetProperties();
    
            for (int i=0;i<prop.Count();i++)
            {
                var propertyInfo = prop[i];
                if (propertyInfo.PropertyType.Namespace != "System")
                {
                    if (propertyInfo.PropertyType.IsGenericType &&
                        propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof (List<>))
                    {
                        Type itemType = propertyInfo.PropertyType.GetGenericArguments()[0]; 
                        var listObjectProperties = itemType.GetProperties();
                        prop = prop.Union(listObjectProperties).ToArray();
    
                    }
                    else
                    {
    
                        var childProp = propertyInfo.PropertyType.GetProperties();
                        prop = prop.Union(childProp).ToArray();
                    }
                }
            }