<> operators in <T>(T[] array)

When I try to run this code:

    public static bool IsSolvable<T>(T[] array){
        int inversions = 0;

        for (int i = 1; i < array.Length; i++) {
            for (int j = i + 1; j < array.Length; j++) {
                if (array [j] > array [i]) {
                    inversions++;
                }
            }
        }
        return inversions % 2 == 0;
    }

I get an error “Operator > cannot be applied to operands of type ‘T’ and ‘T’”.
The array I’m giving this function is an int array. How can I make this work?

the type T is totaly Generic, you are doing array [j] > array , you are supossing here the array implement the operator “>” but if you use a list of Object the compiler can’t do object > object.
change the param of your function as public static bool IsSolvable(int[ ] array)

Constrain the method to IComparable (an interface that int and most value types implement) and use the compareTo method

public static bool IsSolvable<T>(T[] array)
    where T: IComparable<T>
{
        int inversions = 0;
        for (int i = 1; i < array.Length; i++) {
            for (int j = i + 1; j < array.Length; j++) {
                if (array [j].CompareTo(array [i]) > 0) {
                    inversions++;
                }
            }
        }
        return inversions % 2 == 0;
    }
3 Likes

That worked, thanks :slight_smile:
(had to add “System” to the used libraries 1-st tho)

EDIT: Is there a way for me to assign the value to an int variable?

int a = array[0];

this doesn’t work. Neither does this:

int a = (int) array[0];

its a generic method so you likely want to keep it referenced as a generic type (i.e. T a = array[0]; ). perhaps if you show your code we can give a more specific answer.