Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code a truly generic tree using Generics

Tags:

c#

.net

generics

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?

like image 960
logicnp Avatar asked May 21 '26 04:05

logicnp


1 Answers

How do you define a generic tree for such cases?

I wouldn't try to in the first place. If what I wanted to model was:

  • I have a list of documents
  • A document has a list of paragraphs
  • A paragraph has a list of words

then why do you need generic nodes at all? Make a class Paragraph that has a List<Word>, make a class Document that has a List<Paragraph>, and then make a List<Document> and you're done. Why do you need to artificially impose a generic tree structure? What benefit does that buy you?

like image 160
Eric Lippert Avatar answered May 23 '26 18:05

Eric Lippert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!