how do you determine if a property is one of my defined classes using systemreflection

With Reflection you can query the properties for any type. Note that structs may also have properties. So it would make sense to recurse all the types, not just classes.

But note that this might not make sense for some built-in types like string having a Length property and DateTime having many properties like DayOfWeek and Ticks. And worse, it has a property Date being a DateTime again, creating an infinite recursion. So by trial an error you might have to exclude some types or even implement a mechanism detecting recursions or at least limit the maximum level of nesting.

Here an example with exclusions:

private static readonly HashSet<Type> ExcludedTypes = 
    new HashSet<Type> { typeof(string), typeof(DateTime) };

static void GetValues(Object obj, int level)
    Type t = obj.GetType();
    PropertyInfo[] properties = t.GetProperties();
    foreach (var property in properties) {
        if (property.GetIndexParameters().Length == 0) { // Exclude indexers
            Console.Write(new string(' ', 4 * level));
            Type pt = property.PropertyType;
            object value = property.GetValue(obj, null);
            Console.WriteLine($"{pt.Name} {property.Name} = {value}");
            if (value != null && !ExcludedTypes.Contains(pt)) {
                GetValues(value, level + 1);

Result of calling GetValues(new c(), 0);
(I added DateTime a3 and Point b3 properties to make it more interesting):

String c1 = vc1
Int32 c2 = 60
a class_a = StackOverflowTests3.RecurseProperties+a
    String a1 = va1
    Int32 a2 = 20
    DateTime a3 = 23.10.2020 16:55:01
b class_b = StackOverflowTests3.RecurseProperties+b
    String b1 = vb1
    Int32 b2 = 40
    Point b3 = {X=7,Y=3}
        Boolean IsEmpty = False
        Int32 X = 7
        Int32 Y = 3

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top