Search code examples
c#reflectionpropertyinfo

Reflection: Get all subproperties


I have a List that contains objects and each of these objects contains a lot of properties of several types, and each of these properties contains subproperties aswell.

I need to get all the properties via Reflection and store them in one PropertyInfo[] ...

Is this even possible with reflection? I really need to do it via reflection...


Solution

  • There is no such thing as "sub properties" - properties are of a certain type, can have values of a certain type (ie. a subclass of the property type), and that type can have properties of its own.

    You can use recursion for this:

    List<PropertyInfo> properties = new List<PropertyInfo>();
    foreach (object obj in myList)
    {
        properties.AddRange(GetDeepProperties(obj, ...));
    }
    
    PropertyInfo[] array = properties.ToArray();
    

    ...

    IEnumerable<PropertyInfo> GetDeepProperties(object obj, BindingFlags flags)
    {
        // Get properties of the current object
        foreach (PropertyInfo property in obj.GetType().GetProperties(flags))
        {
            yield return property;
    
            object propertyValue = property.GetValue(obj, null);
            if (propertyValue == null)
            {
                // Property is null, but can still get properties of the PropertyType
                foreach (PropertyInfo subProperty in property.PropertyType.GetProperties(flags))
                {
                    yield return subProperty;
                }
            }
            else
            {
                // Get properties of the value assiged to the property
                foreach (PropertyInfo subProperty = GetDeepProperties(propertyValue))
                {
                    yield return subProperty;
                }
            }
        }
    }
    

    The above code is just an example:

    • I have not tried or even compiled it
    • you'll get a StackOverflowException if somewhere in this "property tree" objects are pointing to eachother
    • it misses null checks and exception handling (property getters can throw exceptions)
    • it ignores the existence of indexed properties

    I don't know what you want to do with this array - the reference to the object from which each PropertyInfo was created is lost, so you can't get or set their values anymore.