Search code examples
c#.netlinqgenericsicomparable

Implementing IComparable<T> Interface for a generic class to compare type T


I tried using IComparable<T> in a generic class to compare elements of type T and I get the following error:

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

I was wondering if there could be a work around that. Here is a simple example that IComparable<T> is working when I define my class to take int:

public class IntStack : IComparable<IntStack>
{
    public int[] stack = new int[2];

    public int CompareTo(IntStack other)
    {
        // If the current stack < other stack return -1
        // If the current stack > other stack return +1
        // If current stack entries == other stack entries return 0
        for (var current = 0; current < 2; current++)
        {
            if (stack[current] < other.stack[current])
            {
                return -1;
            }
            else if (stack[current] > other.stack[current])
            {
                return 1;
            }
        }
        return 0;
    }
}

IComparable<T> is now not working here when I change the class above to take generic:

public class Mystack<T> : IComparable<Mystack<T>> where T : IComparable
{
    public T[] stack = new T[2];

    public int CompareTo(Mystack<T> other)
    {
        // If the current stack < other stack return -1
        // If the current stack > other stack return +1
        // If current stack entries == other stack entries return 0
        for (var current = 0; current < 2; current++)
        {
            if (stack[current] < other.stack[current])
            {
                return -1;
            }
            else if (stack[current] > other.stack[current])
            {
                return 1;
            }
        }
        return 0;
    }

Solution

  • The reason why you are getting this error is that you cannot use inequality operators ("<", ">") with IComparable, unless you override them.

    You can use CompareTo() instead.

    public class Mystack<T> : IComparable<Mystack<T>> where T : IComparable
    {
    public T[] stack = new T[2];
    
    public int CompareTo(Mystack<T> other)
    {
        // If the current stack < other stack return -1
        // If the current stack > other stack return +1
        // If current stack entries == other stack entries return 0
        for (var current = 0; current < 2; current++)
        {
            if (stack[current].CompareTo(other.stack[current]) < 0)
            {
                return -1;
            }
            else if (stack[current].CompareTo(other.stack[current]) > 0)
            {
                return 1;
            }
        }
        return 0;
    }