1

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.

4 Answers4

0

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;

Daniel van Heerden
  • 836
  • 1
  • 7
  • 25
0

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";

Working Example

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
0

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);
Diligent Key Presser
  • 4,183
  • 4
  • 26
  • 34
0

To do this fully you could use the System.Linq.Dynamic library as discussed in this question. There's other libraries mentioned there too.

Community
  • 1
  • 1
smead
  • 1,768
  • 15
  • 23