dimanche 2 septembre 2018

Recursively iterating through object's properties throws StackOverflowException

I'm recursively iterating through an object's properties using the following method:

void GetProps(object obj)
{
    if (obj == null)
        return;

    var objType = obj.GetType();
    var properties = objType.GetProperties();

    foreach (var property in properties)
    {
        object value = property.GetValue(obj, null);

        if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType))
        {
            var enumerable = (IEnumerable)value;

            foreach (object child in enumerable)
                GetProps(child);
        }
        else
        {
            GetProps(value);
        }
    }
}

The object is very complex (over 30 classes). I'm getting a StackOverflowException when going deeper into the object at GetProps(value.

Is there a way to catch the exception and check why it's failing, and, solve the problem?





Aucun commentaire:

Enregistrer un commentaire