Home » c# » c# – Evaluate string expression and convert to bool?-Exceptionshub

c# – Evaluate string expression and convert to bool?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I want to evaluate the string expression and convert the result to bool.

For example

string expression = !((71 > 70) && (80 > 71)) || 72 < 71 ;

the above expression has to evaluate and return true.

Can anyone suggest how to evaluate the expression and return bool value?

How to&Answers:

I dont believe there is any built in expression solver that can be leveraged for this kind of expression evaluation. I would recommend Microsoft.CodeAnalysis.CSharp.Scripting to do the evaluation.

string expression = "!((71 > 70) && (80 > 71)) || 72 < 71";
bool output = CSharpScript.EvaluateAsync<bool>(expression).Result;
// -> false

Issues with your question

  • The expression will not evaluate to true. I dont know why you assume that and require that it does. After the execution of the above script, the resultant bool will be false.

!((71 > 70) && (80 > 71)) || 72 < 71
!((true) && (true)) || false
!(true & true)
false

  • you cannot declare a string without quotes; string express = "within quotes";. Statement above in post (string expression = !((71 > 70) && (80 > 71)) || 72 < 71 ;) is not a valid C# statement.

Test snippet here at #dotnetfiddle

Answer:

You can use the NCalc package. The code below produces “False”

using System;
using NCalc;

public class Program
{
    public static void Main()
    {
        Expression e = new Expression("!((71 > 70) && (80 > 71)) || 72 < 71");
        bool v = (bool)e.Evaluate();
        Console.WriteLine(v.ToString());
    }
}

.Net Fiddle: https://dotnetfiddle.net/02c5ww

Answer:

If your requirement is to get expressoin output as string “true” then use this,

string expression = Convert.ToString(!((71 > 70) && (80 > 71)) || 72 < 71);

And if requirement is to get bool “true” then use this,

bool expression = !((71 > 70) && (80 > 71)) || 72 < 71;

But your expression is like it will return false, to make it true remove “!” as below,

string expression = Convert.ToString(((71 > 70) && (80 > 71)) || 72 < 71);            
bool bool_expression = ((71 > 70) && (80 > 71)) || 72 < 71;