tags:

views:

316

answers:

5

Is it possible to have a dynamic operator in c#?

string aString = "5";
int a = 5;
int b = 6;
string op = "<";

//want to do something like dynamically without checking the value of op
if( a op b)
+1  A: 

C# 4.0 will have a dynamic keyword for dynamic typing.

Michaël Larouche
Limited to v2 atm
JL
Why do want a dynamic operator ? Maybe you should try using generics or downcast to object
Michaël Larouche
Interoperation with the dynamic framework and languages mainly.
Dykam
It won't help him here anyway, as it doesn't do `eval` - which is what he effectively wants.
Pavel Minaev
I know what the dynamic keyword is supposed to do :P
Michaël Larouche
+10  A: 

You can't create dynamic operators - but you can wrap an operator in a delegate. You can use lambdas to simplify the syntax.

Func<int,int,int> opPlus = (a,b) => a + b;
Func<int,int,int> opMinus = (a,b) => a - b;
// etc..

// now you can write:
int a = 5, b = 6;
Func<int,int,int> op = opPlus;
if( op(a,b) > 9 )
    DoSomething();

Although it's not definite - the future direction for C# is to implement the compiler as a service. So, at some point, it may be possible to write code that dynamically evaluates an expression.

LBushkin
A: 

You might find something like Flee helpful. There are others, but their names escape me right now.

John Sheehan
+1  A: 

Piggybacking on LBushkin's response:

Func<int, int, bool> AGreaterThanB = (a,b) => a > b;
Func<int, int, bool> ALessThanB    = (a,b) => a < b;

Func< int, int, bool> op = AGreaterThanB;

int x = 7;
int y = 6;

if ( op( x, y ) ) 
{
    Console.WriteLine( "X is larger" );
}
else
{
    Console.WriteLine( "Y is larger" );
}

http://msdn.microsoft.com/en-us/library/bb549151.aspx

rp