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?
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:
Drawbacks:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With