Is it recursive or iterative?

If you look at it calling the FindChildControls method in the lower (inner) foreach statement, since it comes from foreach, does that make it recursive or iterative?

Thanks!

public static IEnumerable<T> FindChildControls<T>(this ControlCollection controlCollection) where T: class { foreach(Control control in controlCollection) { if(control is T) { yield return control as T; } foreach(T type in control.Controls.FindChildControls<T>()) { yield return type; } } } 
+4
source share
2 answers

Here you will learn recursive methods. Each well-written recursive method has the same basic form:

 Method(Arguments) --> Result If Arguments are easy Return the easy result Else Make arguments for a simpler version of the problem Call Method one or more times with those arguments Combine the results and return the combined result 

For instance:

 static int Height(Tree t) { if (t == null) return 0; else { int leftHeight = Height(t.Left); int rightHeight = Height(t.Right); return Math.Max(leftHeight, rightHeight) + 1; } } 

Classical recursive function. First, determine if we are in the base case, a case that cannot be reduced further. If so, excellent. If not, find one or more smaller problems, solve them recursively, and then combine their results into the result of this problem.

Your method is clearly recursive. First he checks to see if he is in the base case. The main case is that the argument has no child controls, in which case it either returns a sequence containing itself or returns an empty sequence. The recursive case is that the argument has child controls, in which case it returns the result by calculating the results from the children and combining it with the result of the argument itself. There is a base case and a recursive case that reduces the problem to smaller versions, so it is a recursive method.

+8
source

This method is recursive because it calls itself on line 9. It also uses iterations ( foreach loops). He is also lazy, as he gives results, therefore, if the caller does not miss the counter, nothing will be done.

+11
source

All Articles