I want to write a method which can take an arbitrary array of a numeric type and return the sum of all the elements between startIndex and endIndex. This is what I have:
private static T SumArrayRange<T>(T[] scores, int startIndex, int endIndex)
{
T score = 0;
for (int i = startIndex; i <= endIndex; i++)
{
score += scores[i];
}
return score;
}
But the compilation fails with these 2 errors.
- Cannot implicitly convert type 'int' to 'T'.
- Operator '+=' cannot be applied to operands of type 'T' and 'T'
Is there any way I can force T to be only one of the numeric types (long, double etc.)? Or is their a more elegant way of solving this?