I'm trying to do arithmetic operations based on the operators passed as method parameter. I can perform this in many ways but problem is I've a datatable to be operated upon. I cannot pass particular data row as I have many datarows to be operated on.
What I have done: I know this can be done in delegate style. something like in the answer - https://stackoverflow.com/a/44333156
public int MainOperationSimplifeid(Func<int, int, int> operatoru)
{
if (beforeoperation == 2)
{
a2 = Convert.ToInt32(textBox1.Text);
textBox1.Text = "";
result = operatoru(a1, a2);
// textBox1.Text = Convert.ToString(result);
a1 = 0;
a2 = 0;
}
beforeoperation++;
return result;
}
I know, I can also achieve this by using enum or switch or even by method overloading. But my code is already huge and complex with multiple supporting methods. So I don't want to add more complexities.
What I need: Can I do it something like this?
void MethodName(DataTable dt, int operand, char op)
{
//few lines of code
dt.SomeRowName1 = (double)dtRowValue op operand;
//few lines of code
dt.SomeRowName2 = (double)dtRowValue op operand;
dt.SomeRowName3 = (double)dtRowValue op operand;
//few lines of code
}
I want to achieve this in a very generic way (code reusability) rather than doing method overloading or switch for different operators and writing same lines of codes again and again.
You can search for the operator method with reflection, then create a delegate from it.
This method should work for numeric types since .Net 6.
If you are concerned about efficiency, you can cache the results.
If you want to know which values "op" can take, please check the long "Implements" list in the document of the corresponding type --> https://learn.microsoft.com/en-us/dotnet/api/system.int32.
It can be more generic by specifying the type of each parameter in the operator.
Here's another example of using expressions and reflection to create operator methods, this can also be used in .Net Framework.
The supported op values can be found here: https://learn.microsoft.com/en-us/dotnet/api/system.linq.expressions.binaryexpression#binary-arithmetic-operations