1

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;
}
3

2 Answers 2

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

3

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).

2 Comments

Good answer @Servy - this is basically why these interfaces exist.
@p.s.w.g Looks like there was some serial voting on my account. That should account for at least one, if not both of the DVs. We'll see whether both or just one goes away tonight.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.