4

Essentially, I'm trying to write a generic bruteforce getMax() method 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 won't compile, with the error Operator '>' cannot be applied to operands of type 'T' and 'T'. I gave the IComparable directive, so I'm not sure what's going on here. Why does this not work?

Jim
  • 4,509
  • 16
  • 50
  • 80
  • Rather than passing the rows and columns to the method you can just use `GetLength` to find the dimensions, unless you specifically want to search a subset of the matrix. – Servy Feb 26 '13 at 18:21

3 Answers3

7

You must use CompareTo() rather than the > operation.

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

In your case you'd put:

if (matrix[row, col].CompareTo(max_val) > 0)
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
2

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

if (matrix[row, col].CompareTo(max_val) > 0) {
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
1
if (matrix[row, col] > max_val)

Should be

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

Since IComparable provides only CompareTo not >.

Guvante
  • 18,775
  • 1
  • 33
  • 64