I have a class in C# where I would like to implement methods to do operations in generics array. For example, I would like to get the maximum component value from a generic array. In my case, it would be enough to consider just numeric types (int, long, double...)
public class NumericCalculation<T> where T : IComparable<T>
{
public static T getMax (T[] array)
{
T maxValue = default(T);
if ( array.Length > 0) {
maxValue = array[0];
for (int i = 0; i < array.Length; i++) {
if (array[i] > maxValue)
{
maxValue = array[i];
}
}
}
return maxValue;
}
}
But this returns the error : "Error 2 Operator '>' cannot be applied to operands of type 'T' and 'T'"
Is there an interface that I am skipping or something? Is possible to do this generic method to generic arrays of numbers?
Thank you!
Sounds like you just want:
return array.DefaultIfEmpty().Max();
But to answer your specific question, you can use CompareTo, which is a member of the IComparable<T> interface that you have constrained the array element-type to:
if(array[i].CompareTo(maxValue) > 0) { ... }
But personally, I would use Comparer<T>.Default instead as it handles null references better. This isn't all that important in your case as you are only interested in primitive numeric value-types (all structs):
if(Comparer<T>.Default.Compare(array[i], maxValue) > 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