Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to parameterize operator in c#

Tags:

c#

generics

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 ?

like image 347
user310291 Avatar asked Dec 05 '22 10:12

user310291


1 Answers

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>.

like image 80
Sergey Kalinichenko Avatar answered Dec 15 '22 00:12

Sergey Kalinichenko