Is it possible to specify an operator R
where R
can be an arithmetic, relational or logical operator ?
For example a function that calculates
c = a R b
where I can specify whether R
is +, -, *, /
Can this be done in C# ?
A binary operator is any function which accepts two operands. It is simple to abstract this functionality using delegates, which are basically wrappers around methods (functions).
To make this clearer, we can define a generic method which does nothing more that invoke the delegate using specified parameters, and return its result:
public Tout GetResult<TIn, TOut>(TIn a, TIn b, Func<TIn, TIn, TOut> @operator)
{
return @operator(a, b);
}
And you could use it to pass any combination of parameters and operators:
private bool AreEqual(int a, int b)
{
return a.Equals(b);
}
private int Subtract(int a, int b)
{
return a - b;
}
You can then use the same generic method to do whatever operation you want:
// use the "AreEqual" operator
bool equal = GetResult(10, 10, AreEqual);
// use the "Subtract" operator
int difference = GetResult(10, 10, Subtract);
Using lambda expressions, you can even create the operator "on the fly", by specifying it as an anonymous method:
// define a "Product" operator as an anonymous method
int product = GetResult(10, 10, (a,b) => a*b);
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