When I try to run this code: Code (csharp): 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<T> 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<T> (an interface that int and most value types implement) and use the compareTo method Code (CSharp): 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; }
That worked, thanks (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? Code (csharp): int a = array[0]; this doesn't work. Neither does this: Code (csharp): 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.