So, i'm very new to C#, and i'm trying to evaluate if statements in a string. Here's an example:
string toEval = "5 > 4";
I want this to return true if 5 is bigger than 4.
So, i'm very new to C#, and i'm trying to evaluate if statements in a string. Here's an example:
string toEval = "5 > 4";
I want this to return true if 5 is bigger than 4.
Just remove your inverted commas. You possibly need to include a .ToString() if you want it in string form string toEval = (5 > 4).ToString()
however if the value is what you are after then you probably want bool toEval = 5 > 4;
The operator >
is a predefined arithmetic operator for comparing two numeric values you cannot applied it on string values. To complete your requirement you can implement the scenario like this:
Let a
and b
are two string variables of integer type and are initialized with 5
and 4
respectively. toEval
be the output variable.
int a = 5, b = 4;
string toEval = "";
if (a > b)
toEval = "A is bigger than B";
else
toEval = "B is bigger than A";
There is an Expression
class in .NET, which is pretty exciting, but sadly, there is no built-in Expression
parser.
But you still can evaluate simple math expresions this way:
var evaluator = new DataTable();
string toEval = "5 > 4";
bool result = (bool)evaluator.Compute(toEval, string.Empty);
To do this fully you could use the System.Linq.Dynamic library as discussed in this question. There's other libraries mentioned there too.