Home > Software design >  Returning a List of Nodes that are Generic Types C#
Returning a List of Nodes that are Generic Types C#

Time:01-28

I am learning about generics and there's clearly something basic I am not understanding about them.

I have a Node class and a function that will populate a binary tree of nodes and return this tree as a list. I want the nodes to have a generic data type for their values so I made the Node class like this:

class Node<T>
    {
        public T dataval;
        public Node<T> left;
        public Node<T> right;
        public Node(T data)
        {
            this.dataval = data;
            this.left = null;
            this.right = null;
        }

    }

Now when creating the function, I am trying to make new Nodes with a primitive type such as an int or char. Here's what I have tried and the errors I am getting.

public static List<Node<T>> createTree<T>(int length) 
{   
                //    a
                //   / \ 
                //  b   c
                // / \   \
                //d   e   f
            Node<T> a = new Node<T>(1);     // cannot convert from 'int' to 'T'
            Node<T> b = new Node<int>(2);   // cannot implicitly convert 'Node<int>' to 'Node<T>'
            Node<int> c = new Node<int>(3);  // No error here, but error in return statement     
            var d = new Node<int>(4);     // No errror here, but error in return statement
            var e = new Node<int>(5);
            var f = new Node<int>(6);
            a.left = b;
            a.right = c;
            b.left = d;
            b.right = e;
            c.right = f;

            return new List<Node<int>> { a, b, c, d, e, f};  // cannot convert from 'Node<int>' to 'Node<T>'
             
}

I think my misunderstanding of generics begins with creating these new objects and instantiating them with a primitive data type. Not sure what's going wrong with this process.

CodePudding user response:

Your generic createTree<T> method promises to create a tree whatever the type T might be. So clearly you cannot assume that T is int.

Option 1: make the method specifically create a tree of ints:

Change the signature to List<Node<int>> createTree(int length) and use Node<int> in the body whereever you now have Node<T>.

Option 2: pass the values from outside

If you want to keep the method generic, you need to provide the values of correct type from the caller.

This could be done in the form of additional parameters of type T like List<Node<T>> createTree<T>(T aval, T bval, T cval, T eval, T fval) or List<Node<T>> createTree<T>(T[] values) or in the form of a factory method List<Node<T>> createTree<T>(Func<T> valueFactory)

  • Related