Search code examples
c#methodscallbinary-treeicomparable

C# - How can I call a method from another 'class ClassName<T> where T : IComparable'


In my 'Program.cs' I am trying to call method 'inOrder()' from another class 'BinTree.cs'.

Class BinTree starts with class BinTree<T> where T : IComparable

I've tried:

inOrder();

and

BinTree<T>.inOrder();

and

BinTree<int>.inOrder();

But none of these work.

Thanks for looking.

EDIT:

class Program
{
    static void Main(string[] args)
    {
        Node<int> tree = new Node<int>(6);
        tree.Left = new Node<int>(2);
        tree.Left.Right = new Node<int>(5);

        tree.Left.Right.Data = 3;

        tree.Right = new Node<int>(8);



        (new BinTree<int>()).inOrder();

    }

EDIT2:

    private Node<T> root;
    public BinTree()  //creates an empty tree
    {
        root = null;
    }
    public BinTree(Node<T> node)  //creates a tree with node as the root
    {
        root = node;
    }

Solution

  • From what I can tell, you need to create a BinTree<int> instance and pass in your Node<int> instance on the constructor. Something like this:

    class Program
    {
        static void Main(string[] args)
        {
            // Create Node instances for tree
            Node<int> node = new Node<int>(6);
            node.Left = new Node<int>(2);
            node.Left.Right = new Node<int>(5);
            node.Left.Right.Data = 3;
            node.Right = new Node<int>(8);
    
            // Create tree, set root node
            BinTree<int> tree = new BinTree<int>(node);
            tree.inOrder(); // Call inOrder method of tree instance
        }
    }