How to code a truly generic tree using Generics

.net, c#, generics

Solution

If you want a strict hierarchy of types you could declare them like this:

class Node<T, TChild> {...}

Node<Document, Node<Paragraph, Node<Line, Word>>>

I did not claim it would be pretty. :)

Problem

Lets say I have a Node class as follows: ``` class Node<T> { T data; List<Node<T>> children; internal Node(T data) { this.data = data; } List<Node<T>> Children { get { if (children == null) children = new List<Node<T>>(1); return children; } } internal IEnumerable<Node<T>> GetChildren() { return children; } internal bool HasChildren { get { return children != null; } } internal T Data { get { return data; } } internal void AddChild(Node<T> child) { this.Children.Add(child); } internal void AddChild(T child) { this.Children.Add(new Node<T>(child)); } } ``` The problem is that each and every node of the tree is confined to a single type. However, there are situations where the root node is of one type, which has children of another type which has children of a third type (example documents-->paragraphs-->lines-->words). How do you define a generic tree for such cases?

Original source