Charu
Charu

Reputation: 2727

generic method not supporting constraints

I am trying to write a generic method which should support intrinsic types for ex int, double, float etc. The method is sorting the array. I am getting a compile time error saying "cannot apply operator < to type T" which I understand, but how can I resolve it? Should I make the class generic and use constraints? Here is my code:

public static T[] Sort<T>(T[] inputArray) 
{
    for (int i = 1; i < inputArray.Length; i++)
    {
        for (int j = i - 1; j >= 0; j--)
        {
            ***if (inputArray[j + 1] < inputArray[j])***
            {
                T temp = inputArray[j + 1];
                inputArray[j + 1] = inputArray[j];
                inputArray[j] = temp;
            }
            else
            {
                break;
            }
        }
    }
    return inputArray;
}

Upvotes: 1

Views: 116

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149078

C# doesn't support generic constraints on what operators a type supports. However, .NET provides a number of interfaces that provide similar functionality. In this case, you need to add a generic constraint to ensure that T implements IComparable<T>.

public static T[] Sort<T>(T[] inputArray) where T : IComparable<T>
{
    for (int i = 1; i < inputArray.Length; i++)
    {
        for (int j = i - 1; j >= 0; j--)
        {
            if (inputArray[j + 1].CompareTo(inputArray[j]) < 0)
            {
                T temp = inputArray[j + 1];
                inputArray[j + 1] = inputArray[j];
                inputArray[j] = temp;
            }
            else
            {
                break;
            }
        }
    }
    return inputArray;
}

Upvotes: 5

Servy
Servy

Reputation: 203850

There is no generic constraint that you can apply that will restrict types to those that have overloaded the < operator.

The best that you can do is restrict the type to those that implement IComparable<T> or accept a parameter of type IComparer<T> to do the comparisons (having two methods, one with each option, could also be worth doing).

Upvotes: 3

Related Questions