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.
Actually, this should be closer to what you want.
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 tof, which makes it pretty much impossible.