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?
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)
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) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With