I couldn’t find the answer from searching, but maybe I’m not asking it the right way. I have a program with lots of matrix-type functions that take in 3D matrices (in the form of 1D-2D jagged arrays) and performs functions on elements. However I often need to use the same function but with differently typed arguments: int[][,] and float[][,] and double[][,].
So far I’ve just been rewriting the same method but changing the type, but I have tons of these things and it’s a real pain to keep rewriting “re-typed” methods.
private float SomeFunctionA(float[][,] d)
{
float sum = 0;
for (int k = 0; k < d.GetLength(0); k++)
for (int j = 0; j < d[0].GetLength(1); j++)
for (int i = 0; i < d[0].GetLength(0); i++)
sum += d[k][i,j];
return SomeFunctionB(sum);
}
private float SomeFunctionA(double[][,] d)
{
double sum = 0;
for (int k = 0; k < d.GetLength(0); k++)
for (int j = 0; j < d[0].GetLength(1); j++)
for (int i = 0; i < d[0].GetLength(0); i++)
sum += d[k][i,j];
return SomeFunctionB(sum);
}
Is there an easier way to allow different types? It would be great if there was a way to have a generic main method with the functionality (i.e. the 3 for loops and other body code), and then helper methods which take a different type and call the generic method for each case.
Thanks all.
There is no operator constraints in C# generics so I woul use next:
For this solution you may create few more classes but you may support any operator (not only +) in this case.