rohit89
rohit89

Reputation: 5773

programmatically specify operator

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

Upvotes: 11

Views: 1270

Answers (4)

svick
svick

Reputation: 245038

You can do something very close to that using lambda:

Func<int, int, int> op = (x, y) => x + y; // or any other operator

And then use it like any other delegate:

int result = op(1, 2);

If the type in question were user-defined with overloaded operators, you could use reflection, but I'm afraid it's not possible for types like int.

Upvotes: 2

vgru
vgru

Reputation: 51292

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);

Upvotes: 7

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

Check out Expression Trees - http://msdn.microsoft.com/en-us/library/bb397951.aspx

Upvotes: 0

Alexander Beletsky
Alexander Beletsky

Reputation: 19841

It is possible to have operator overloading in C#, check some MSDN

http://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx

Upvotes: -3

Related Questions