0

I'm trying to build a property inspector method that iteratively inspects all an objects properties and recursively examines all of the sub-properties of those properties until it either runs out of properties or reaches the max recursion level/depth.

However I am running into an issue in tracking the recursion depth due to the fact that the recursion takes place inside of a iterative loop, therefore each property of an object increments the recursion depth, when it shouldn't, only the next level down should.

Here is my example code:

Dim MaxRecursionLevel As Integer = 10
Dim CurrentRecursionLevel As Integer = 1

Function GetPropertiesWithName(objToSearch as Object, optional nameFilters as String()

dim result as new List(of Object)
If CurrentRecursionLevel > MaxRecursionLevel Then Exit Function
CurrentRecursionLevel = CurrentRecursionLevel + 1

'Iteration of properties
For Each item As PropertyInfo In objToSearch.GetType.GetProperties() 
    if PropertyHasName(nameFilters) Then
        result.Add(item)
        dim subItem as Object = item.GetValue(objToSearch, Nothing)

        'Recursion of Subproperties
        dim subResult as List(of Object) = GetPropertiesWithName(subItem, nameFilters)
        if not subResult is Nothing then result.Addrange(subResult)
    End If
Next
Return result
End Function

How can I accurately track the recursion depth, or is there a better way to go about this?

1
  • Where do you actually increase CurrentRecursionLevel? Commented Feb 22, 2016 at 8:06

2 Answers 2

3

Instead of using a global variable to track recursion, pass in the current recursion level as a parameter to your function. At the top of the function, check if the passed in value exceeds the maximum, and return immediately if it does.

Sign up to request clarification or add additional context in comments.

1 Comment

This hasn't worked for what I was trying to do, but I believe it was an issue with the structure of my application, not the solution that is causing this. So i've awarded the answer to the first one in :)
3

In resepect to Nicks answer:

Function GetPropertiesWithName(objToSearch as Object, currentRecusrionLevel as Integer, optional nameFilters as String())
  If currentRecusrionLevel > MaxRecursionLevel Then Return new List(Of Object)
  '...
  For Each item As PropertyInfo In objToSearch.GetType.GetProperties() 
    '...
    Dim subResult as List(of Object) = 
         GetPropertiesWithName(subItem,currentRecusrionLevel + 1, nameFilters)
  '...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.