Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic function unable to compare between an array value and a standard value [duplicate]

Tags:

c#

generics

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?

like image 921
Jim Avatar asked Dec 26 '22 08:12

Jim


2 Answers

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)
like image 85
Matthew Watson Avatar answered May 13 '23 22:05

Matthew Watson


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) {
like image 31
tvanfosson Avatar answered May 13 '23 20:05

tvanfosson