Evaluating an arbitrary string expression in c#

303 Views Asked by At

I have a method that needs to return true or false based upon a string expression that is passed in to it. The string expression could look like:

("ASDF"=="A" || "BED"!="BED") && (5>=2)

or any valid C# expression that evaluates to a Boolean result. I only need to support basic string and math comparison operators plus parentheses. I have tried NCalc but when I pass it this:

"GEN"=="GEN" || "GEN"=="GENINTER"

it generates the error System.ArgumentException: Parameter was not defined (Parameter 'GEN') at NCalc.Domain.EvaluationVisitor.Visit(Identifier parameter)

when I use the following code:

NCalc.Expression e = new(filterExpression, EvaluateOptions.IgnoreCase); var filterResultObject =e.Evaluate();

Any thoughts appreciated on how to evaluate an arbitrary expression since I will not know the expression until run time.

Greg

3

There are 3 best solutions below

0
On BEST ANSWER

I have found that NCalc will properly evaluate the strings but only if they are single quoted such as !('GEN'=='GEN'). If the strings are double quoted, the error is thrown.

0
On

For your example you can use NFun package like this:

string str =  "\"ASDF\"==\"A\" || \"BED\"!=\"BED\") && (5>=2)"
bool result = Funny.Calc<bool>(str)
0
On

Another option is to use DynamicExpresso library. Example usage:

var interpreter = new Interpreter();
bool result = (bool)interpreter.Eval("\"GEN\" == \"GEN\" || \"GEN\" == \"GENINTER\"");

They also have an online tool to test expressions.