Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Is there a way to use expressions as a variable/parameter?

Tags:

c#

I'd like to know if it is possible to use an expression as a variable/parameter in C#. I would like to do something like this:

int x = 0;
public void g()
{
   bool greaterThan = f("x>2");
   bool lessThan = f("x<2");
}
public bool f(Expression expression)
{
   if(expression)
       return true;
   else
       return false;
}

Here's what I don't want to do:

int x = 0;
public void g()
{
    bool greaterThan = f(x, '<', 2);
}

public bool f(int x, char c, int y)
{
    if(c == '<')
       return x < y;
    if(c == '>')
       return x > y;
}

Really what I'm getting at is a way to get around using a switch or series of if statements for each of: < > <= >= == !=. Is there a way to do it?

Edit: Suppose that the expression is a string, like "x < 2". Is there a way to go from the string to a predicate without using a series of if statements on the condition?

like image 466
David Hodgson Avatar asked Apr 15 '09 21:04

David Hodgson


1 Answers

Its very possible, just not in the exact syntax you have.

int x = 0;
public void g()
{
   bool greaterThan = f(i => i > 2, x);
   bool lessThan = f(i => i < 2, x);
}
public bool f(Func<int,bool> expression, int value)
{
   return expression(value);
}

Actually, this should be closer to what you want.

int x = 0;
public void g()
{
   bool greaterThan = f(() => x > 2);
   bool lessThan = f(() => x < 2);
}
public bool f(Func<bool> expression)
{
   return expression();
}

Reply to Edit

If you want be able to say f("x < 2"), it's going to be almost impossible. Ignoring parsing it (which could get nasty), you have to capture the value of x, but its just a character to f, which makes it pretty much impossible.

like image 157
Samuel Avatar answered Nov 10 '22 00:11

Samuel