Search code examples
c#treenodestype-safety

in c# for type safe tree implementation (typesafe node)


I am looking for /tring to implement a type safe tree implementation in C#.

How can a type safe tree be implemented, without using interfaces (which force to reimplement the tree functionality all over the place) and without using casts?

I have the idea of using tree as common base class, but then type safety is gone. My current approach is usage generics. But I am missing some conversion back to the base type.

Below is a reduced/nonworking example. The idea is that the returned Nodes support the tree functions, and at the same time they also support their base types behaviour. I could use the below class without and inherit from Node, but then then I loose type safety on one hand, and also get problems with inheritance, as the Nodes have already parent classes.

I also toyed with class extensions, but I haven't got anything that is close to a possible solution.

I think i need one small hint on how to continue. Thank you in Advance.

public class Node<T>  // .
{
    public Node<T> parent;
    public List<Node<T>> children;

    protected Node()
    {
        children = new List<Node<T>>();
        parent = null;
    }
    protected Node(Node<T> parent)
        : this()
    {

        this.parent = parent;
        parent.addChildren(this);
    }


    protected void addChildren(Node<T> child)
    {
        children.Add(child);
    }
    public Node<T> getRoot() // returns root node
    public List<Node<T>> flatten()  // return 1d-list of all nodes.

}

Solution

  • Here's a type-safe tree implementation:

    public class Tree<T> : List<Tree<T>>
    {
        public T Value { get; set; }
    }
    

    Yes, that's it. Simple.

    Of course, you could add a constructor or two, and make the Value property read-only to make it a little more OOP friendly. And you could easily add the Parent property.