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?
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();
}
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.
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