I am trying to process 2-dimensional arrays with a dynamic mathematical operator.
This is the method in question:
public float[,] Calculate(int[,] a, int[,] b, Func<int,int,float> compute)
{
int columns = a.GetLength(0);
int rows = a.GetLength(1);
float[,] result = new float[columns,rows];
for(int i = 0; i < columns; i++)
{
for(int j = 0; j < rows; j++)
{
result[i,j] = compute(a[i,j], b[i,j]);
}
}
return result;
}
This method is called like this:
int[,] a = new int[2,3] { {2, 6, 19}, {3, -4, 25}};
int[,] b = new int[2,3] { {12, -2, 11}, {1, -11, 0}};
//1
float[,] c = Calculate(a, b, (x,y) => (x+y));
//2
float[,] c = Calculate(a, b, (x,y) => (x-y));
//3
float[,] c = Calculate(a, b, (x,y) => (x*y));
//4
float[,] c = Calculate(a, b, (x,y) => (x/y));
Now, while the version 1 to 3 work flawlessly, version 4 is bound to throw an exception sooner or later. Now one way to handle this is use a try catch block:
try
{
result[i,j] = compute(a[i,j], b[i,j]);
}
catch(DivideByZeroException ex)
{
result[i,j] = 0;
}
This looks like I use try catch for flow-control and I'd rather avoid it (Also, the result is wrong). Is there a way to check for the division operator in the function call and if the operator is /
, check if the second array contains 0 and just return null?