-1

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

Greg W
  • 89
  • 1
  • 7
  • 1
    Have a read through [Rick Strahl's blog post](https://weblog.west-wind.com/posts/2022/Jun/07/Runtime-CSharp-Code-Compilation-Revisited-for-Roslyn) on runtime code generation – Andrew Williamson Jan 16 '23 at 02:57
  • Does the expression contain only string and integer literals, or do you need variables, too? – Klaus Gütter Jan 16 '23 at 07:33
  • Dis you have a look at similar questions? https://stackoverflow.com/questions/56580598/c-sharp-evaluate-a-string-expression-and-return-the-result https://stackoverflow.com/questions/1207809/evalstring-to-c-sharp-code – Klaus Gütter Jan 16 '23 at 07:36
  • 1
    Evaluating user supplied expressions as c# code seem like it might be potentially dangerous. Using a specialized parser should be safer if that is a concern. – JonasH Jan 16 '23 at 07:56
  • Thank you for the comments. Yes, only strings, integers, floats.... no variables. Since the incoming expression is evaluated, I agree that the solution needs to be safe to prevent intentional malformed expressions from causing safety concerns. This is why I'm looking for an 'evaluator' that takes care of parsing, performing the operations, and resulting the answer rather than using runtime code injection which exposes the dangers of intentional injection. – Greg W Jan 16 '23 at 14:10

3 Answers3

0

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.

Greg W
  • 89
  • 1
  • 7
0

For your example you can use NFun package like this:

string str =  "\"ASDF\"==\"A\" || \"BED\"!=\"BED\") && (5>=2)"
bool result = Funny.Calc<bool>(str)
tmt
  • 686
  • 2
  • 10
  • 22
0

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.

Dimitris Maragkos
  • 8,932
  • 2
  • 8
  • 26