I am trying to process two-dimensional arrays with a dynamic math 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 the following:
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 that version 1 through 3 works flawlessly, version 4 will inevitably sooner or later throw an exception. Now one way to handle this is to use the catch try block:
try
{
result[i,j] = compute(a[i,j], b[i,j]);
}
catch(DivideByZeroException ex)
{
result[i,j] = 0;
}
It looks like I'm using try catch to control the flow, and I would prefer to avoid it (also, the result is incorrect). Is there a way to check the split statement in a function call, and if the statement /, check if the second array contains 0 and just returns null?