Let's say I have 2 handlers increment_click and decrement_click which calls common method
In real my method can be much more complex and I'd like to avoid to use syntax like with if
if (operator == "+") {
return value = value + step
}
else {
return value = value - step
}
and do something more generic like this
increment(value, operator, step) {
return value = value <operator> step
}
Is it somehow possible ?
You can make a Dictionary<string,Func<decimal,decimal,decimal>>
and set it up with implementations of your operators, like this:
private static readonly IDictionary<string,Func<decimal,decimal,decimal>> ops = new Dictionary<string,Func<decimal,decimal,decimal>> {
{"+", (a,b) => a + b}
, {"-", (a,b) => a - b}
, {"*", (a,b) => a * b}
, {"/", (a,b) => a / b}
};
Now you can do this:
decimal Calculate(string op, decimal a, decimal b) {
return ops[op](a, b);
}
You can even do this generically with some "magic" from Linq.Expressions
: instead of using pre-built lambdas defined in C#, you could define your lambdas programmatically, and compile them into Func<T,T,T>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With