Search code examples
c#stringcomparisonncalc

Evaluating an arbitrary string expression in c#


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


Solution

  • 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.