Home > Back-end >  C# Gives CS0019 Error: Operator cannot be applied to operands of type 'T' and 'T'
C# Gives CS0019 Error: Operator cannot be applied to operands of type 'T' and 'T'

Time:05-03

Im trying to convert AVL tree to Generic but I faced couple of type errors.

Operator cannot be applied to operands of type 'T' and 'T'

 private Node RecursiveInsert(Node current, Node n)
{
    if (current == null)
    {
        current = n;
        return current;
    }
    else if (n.data < current.data) // Gives Error        {
        current.left = RecursiveInsert(current.left, n);
        current = balance_tree(current);
    }
    else if (n.data > current.data) // Gives Error        {
        current.right = RecursiveInsert(current.right, n);
        current = balance_tree(current);
    }
    return current;
}

///

 public class Node
{
    public T data { get; set; }
    public Node left { get; set; }
    public Node right { get; set; }
    public Node(T data)
    {
        this.data = data;
    }
}
public Node root;

CodePudding user response:

Edit: somehow I managed to cut out a code snippet before I posted this.

First of all, the generic type in the Node class needs to implement the ICompareable interface to do this.

 public class Node<T> where T : ICompareable
 {
     public T data { get; set; }
     public Node<T> left { get; set; }
     public Node<T> right { get; set; }
     public Node<T>(T data)
     {
         this.data = data;
     }
 }

Second of all, ICompareable doesn't overload the '<' and '>' operators. You need to do something like this instead

else if (n.data.CompareTo(current.data) < 0) {
    current.left = RecursiveInsert(current.left, n);
    current = balance_tree(current);
}

CodePudding user response:

You can get a generic comparer from Comparer<T>.Default.

public class Node
{
    public static readonly IComparer<T> comparer = Comparer<T>.Default;
}

Then you can use it to compare generic types.

int c = Node.comparer.Compare(n.data, current.data);

if (c < 0) {
    current.left = RecursiveInsert(current.left, n);
    current = balance_tree(current);
}
else if (c > 0) {
    current.right = RecursiveInsert(current.right, n);
    current = balance_tree(current);
}
  • Related