Q:

Example usage of a custom delegate in c#

I found this question on SO about a tree implementation in C#. I have no idea about delegates and I was wondering how the following code could be used to implement a tree. Also, what would be the most efficient way to keep a track of parent nodes?
delegate void TreeVisitor<T>(T nodeData);

class NTree<T>
{
    T data;
    LinkedList<NTree<T>> children;

    public NTree(T data)
    {
        this.data = data;
        children = new LinkedList<NTree<T>>();
    }

    public void addChild(T data)
    {
        children.AddFirst(new NTree<T>(data));
    }

    public NTree<T> getChild(int i)
    {
        foreach (NTree<T> n in children)
            if (--i == 0) return n;
        return null;
    }

    public void traverse(NTree<T> node, TreeVisitor<T> visitor)
    {
        visitor(node.data);
        foreach (NTree<T> kid in node.children)
            traverse(kid, visitor);
    }        
}

A:

A delegate basically lets you talk about an arbitrary function that meets some criteria, instead of having to know exactly what function you're talking about.
Consider the following code for traversing a tree, and performing an operation on each of the elements:
void DoSomethingToAllNodes(NTree<T> node)
{
    DoSomething(node);
    foreach (var child in node.Children)
        DoSomethingToAllNodes(child);
}

It works, but it's pretty inflexible. We'd have to reimplement the method for each different operation we want to perform on the nodes:
void DoSomethingElseToAllNodes(NTree<T> node)
{
    DoSomethingElse(node);
    foreach (var child in node.Children)
        DoSomethingElseToAllNodes(child);
}

Instead, we can declare a delegate to represent "Any method that takes one NTree<T> as a parameter, and returns nothing", and then we can accept a method that satisfies that as an argument. We can then implement one single Traverse method that handles every possibility, instead of having to reimplement it for each different operation.

