Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating Expression at Runtime

I have a C# Console Application project.

I have a logical expression that is stored in database as nvarchar.

For example, the stored expression is: ((34 > 0) || (US == ES)) && (4312 = 5691)

While my application running, I want to retrieve the expression and evaluate it so that the result will be true or false.

How can I do it at runtime?

like image 235
Ahmet Altun Avatar asked Dec 29 '22 03:12

Ahmet Altun


1 Answers

Here's a rather unusual solution, involving JScript:

  • Create a JScript class with the following code:

    public class JsMath {
        public static function Eval(expression:String) : Object {
            return eval(expression);
        }
    }
    
  • Compile it into a DLL:

    jsc /target:library /out:JsMath.dll JsMath.js
    
  • In your C# project, reference JsMath.dll and Microsoft.JScript.dll

  • Now you can use the Eval method as follows:

    string expression = "((34 > 0) || ('US' == 'ES')) && (4312 == 5691)";
    bool result = (bool)JsMath.Eval(expression);
    

Benefits:

  • no work required to parse the expression, the JScript engine does it for you
  • no need to compile arbitrary code (which can be a big security hole if the code is entered by the user)
  • should work with any simple mathematical or logical expression, as long as it follows the JScript syntax

Drawbacks:

  • no way to pass variables (as far as I know)
  • requires a reference to the JScript assembly (not a big issue in most cases, but I'm not sure this assembly is available in the Client Profile or in Silverlight)
like image 136
Thomas Levesque Avatar answered Jan 09 '23 01:01

Thomas Levesque