Comparison in C #: operator '<' cannot be applied to operands of type T and T,

I created a class and then create a method for the class . BinaryTreeNode<T>

Add(T data)

BinaryTree<T>

When I try to compare the values ​​of objects, the compiler says:

operator '<' cannot be applied to operands of type "T" and "T" .

Example:

  public void AddNode(T data) {
        BinaryTreeNode<T> node = new BinaryTreeNode<T>(data);
        BinaryTreeNode<T> temp = root;

        if (temp.Value < node.Value) // **PROBLEM HERE**
        ...

      

I am using VS08 Express Edition.

+2


source share


3 answers


You have to add the constraint in such a way that T has to implement IComparable<T>

and then use this:

public class BinaryTree<T> where T : IComparable<T>
{
    public void AddNode(T data)
    {
        BinaryTreeNode<T> node = new BinaryTreeNode<T>(data);
        BinaryTreeNode<T> temp = root;

        if (temp.Value.CompareTo(node.Value) < 0)
        ...

      

An alternative is to pass in IComparer<T>

and use this:



public class BinaryTree<T> where T : IComparable<T>
{
    private readonly IComparer<T> comparer;

    public BinaryTree(IComparer<T> comparer)
    {
        this.comparer = comparer;
        ...
    }

    public void AddNode(T data)
    {
        BinaryTreeNode<T> node = new BinaryTreeNode<T>(data);
        BinaryTreeNode<T> temp = root;

        if (comparer.Compare(temp.Value, node.Value) < 0)

      

This is the closest you can get to guarantee the "<" operators - the overloaded operators are static, and there is no way to restrict the type argument to require it.

+8


source


Look at General Constraints to narrow down the types that can be T. That way you can make sure they can be compared using your operator.



Currently T can be any object. For example, if you had a Car object, how would the compiler know what to say if one car is "smaller" or "larger" than the other? This is why you need restrictions.

+1


source


The type (int, string, char [], MyClass, YourClass, etc.) of the value does not support the '<' operation. This is normal for most non-terminated number types, i.e. Int, long, decimal, etc.

T needs to implement the IComparable class so that it can be compared to another object of type T.

So, a function declaration should enforce a constraint on T:

public class BinaryTree<T> where T : IComparable<T>
{
    public void AddNode(T data) 

      

and you have to make sure that no matter what T is, it must implement IComparable.

public class MyData : IComparable<MyData>
{
    public int CompareTo(MyData other)
    {
         // return -1 if 'this' is smaller than other, 0 if equals, 1 otherwise
    }
}

      

In your add function, you call

if( temp.Value.CompareTo(node.Value) < 0 )

      

+1


source







All Articles