Using Delegates with Recursion

Suppose you have a hierarchical object model (i.e. a node has a number of child nodes, and so on) and you wish to run some code for every node in that hierarchy. Recursion (a method which calls itself) is the technique to use, but suppose you don’t know what code should run? Hence a delegate.

In your Node class, add a recursive method like this:

public T RecursiveDelegate<T>(Func<Node, T, T> function, T parentValue)
    T value = function.Invoke(this, parentValue);
    foreach (Node node in this.Nodes)
        node.RecursiveDelegate<T>(function, value);
    return value;

You can then call the method on your root node, passing in the block of code that you want executed for every node in the tree. In this example, we build the tree nodes  for a treeview control.

TreeNode rootNode = node.RecursiveDelegate<TreeNode>((n, parentNode) => 
    TreeNode treeNode = new TreeNode(n.ToString());
    if (null != parentNode)
    node.Tag = n;
    return treeNode; 
}, null);

Note how the function has the parent node as the input parameter, you’re expected to return the treeNode you have created as the output, this allows you to get the rootTreeNode at the end.

This allows us to nicely separate out the object model code, and the recursive function, from the UI controls. Separation of concerns.