1. Description
ExpressionEval is an Expression Evaluator back-office component. The basic way to use the component is to input an expression as a string, parse it, define variables, attach function code and then evaluate the expression. The component should return a value, generally a boolean value but depending of the expression content.
- Input an expression
- Parse it (decode it)
- Define variables, attach function code
- Execute (Evaluate) the expression
- Manage error
- Get the result
Another important point is the management of the errors described in details in a dedicated page.
2. Evaluate an expression: the main steps
The sample below shows the main process of evaluating an expression.
// Using clauses using Pierlam.ExpressionEval; // Create the component ExpressionEval evaluator = new ExpressionEval(); // 1-Create the expression to use string expr= "a=b"; // 2-Parse, Decode the expression evaluator.Parse(expr); // 3-Create variable and provide values evaluator.DefineVarInt("a", 12); evaluator.DefineVarInt("b", 12); // 4-Execute the expression ExecResult execResult= evaluator.Exec(); // 5-check if the execution finished with success if (execResult.HasError) { // error occurs, during the parsing or the execution stage return; }
Using function (attach function code) is explained in another page documentation.
3. Get the result
After the evaluation of the expression finished with success, you can get the result. several methods are available to get the result type. It can be a boolean, an integer, a string or a double value.
// 6-get the result //--is the result an integer value? if(execResult.IsResultInt) { // the result type is an integer, so display it Console.WriteLine("Execution Result (int): " + execResult.ResultInt); } //--is the result a bool value? if(execResult.IsResultBool) { // the result type is a bool, so display it Console.WriteLine("Execution Result (bool): " + execResult.ResultBool); } //--is the result a string value? if(execResult.IsResultString) { // the result type is a string, so display it Console.WriteLine("Execution Result (string): " + execResult.ResultString); } //--is the result a double value? if(execResult.IsResultDouble) { // the result type is a double, so display it Console.WriteLine("Execution Result (double): " + execResult.ResultDouble); }