Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programmatically specify operator

Tags:

operators

c#

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# ?

like image 985
rohit89 Avatar asked May 09 '11 19:05

rohit89


1 Answers

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);
like image 162
Groo Avatar answered Oct 11 '22 04:10

Groo