General function cannot compare array value with standard value

Essentially, I'm trying to write a generic getMax () method for bruteforce for a matrix. Here is what I have:

private T getMax <T>(T[,] matrix, uint rows, uint cols) where T : IComparable<T> { T max_val = matrix[0, 0]; for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) { if (matrix[row, col] > max_val) { max_val = matrix[row, col]; } } } return max_val; } 

This will not compile with the Operator '>' cannot be applied to operands of type 'T' and 'T' error Operator '>' cannot be applied to operands of type 'T' and 'T' . I gave the IComparable directive, so I'm not sure what is going on here. Why is this not working?

+4
source share
3 answers

You should use CompareTo (), not the> operation.

See here: http://msdn.microsoft.com/en-gb/library/system.icomparable.aspx

In your case, you set:

 if (matrix[row, col].CompareTo(max_val) > 0) 
+7
source

Implementing IComparable means that it defines the CompareTo method, not the > operator. You need to use:

 if (matrix[row, col].CompareTo(max_val) > 0) { 
+2
source
 if (matrix[row, col] > max_val) 

Must be

 if (matrix[row, col].CompareTo(max_val) > 0) 

Since IComparable only provides CompareTo not > .

+1
source

All Articles