Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot apply Operator '<' to operands of type T and T

Tags:

c#

.net

generics

so here's my code

public void BubbleSort<T>(T[] array) where T : IComparable<T>
{
    for (int i = 0; i < array.Length; i++)
    {
        for (int j = 1; j < array.Length; j++)
        {
            if (array[j] < array[j - 1])
            {

            }
        }
    }
}

and before you shoot be down for not searching. I have searched and one of the answers here on SO said to use an icomparable interface to solve the problem.

unfortunately i am not going anywhere with this error.

like image 240
Win Coder Avatar asked Nov 10 '13 20:11

Win Coder


1 Answers

It looks like you're expecting the IComparable<T> constraint to allow you to use an inequality operator. IComparable and IComparable<T> say nothing about using inequality operators directly. Instead, what they do are provide a CompareTo() method you can use to simulate the inequality operators:

public void BubbleSort<T>(T[] array) where T: IComparable<T>
{
    for (int i = 0; i < array.Length; i++)
    {
        for (int j = 1; j < array.Length; j++)
        {
            if (array[j].CompareTo(array[j-1]) < 0)
            {

            }
        }
    }
}
like image 60
Joel Coehoorn Avatar answered Oct 18 '22 22:10

Joel Coehoorn