create a method in c# which takes a class object as input parameter and uses reflection to loop through all its properties recursively and returns all boolean propertyinfo as a list in csharp

main.cs
using System;
using System.Collections.Generic;
using System.Reflection;

public static class ReflectionUtils
{
    public static List<PropertyInfo> GetAllBooleanProperties(object obj)
    {
        List<PropertyInfo> booleanProperties = new List<PropertyInfo>();
        Type objectType = obj.GetType();
        PropertyInfo[] properties = objectType.GetProperties();

        foreach (PropertyInfo property in properties)
        {
            if (property.PropertyType == typeof(bool))
            {
                booleanProperties.Add(property);
            }
            else if (property.PropertyType.IsClass && property.GetValue(obj) != null)
            {
                List<PropertyInfo> childProperties = GetAllBooleanProperties(property.GetValue(obj));
                booleanProperties.AddRange(childProperties);
            }
        }

        return booleanProperties;
    }
}
896 chars
29 lines

This method can be called as follows:

main.cs
public class MyClass
{
    public bool MyBoolProperty { get; set; }
    public MyNestedClass MyNestedObject { get; set; } = new MyNestedClass();
}

public class MyNestedClass
{
    public bool MyNestedBoolProperty { get; set; }
}

public static void Main()
{
    MyClass myClass = new MyClass();
    List<PropertyInfo> booleanProperties = ReflectionUtils.GetAllBooleanProperties(myClass);

    foreach (PropertyInfo property in booleanProperties)
    {
        Console.WriteLine(property.Name);
    }
}
503 chars
22 lines

The output of this code snippet will be:

main.cs
MyBoolProperty
MyNestedBoolProperty
36 chars
3 lines

gistlibby LogSnag