Skip to content

Getting Started

Muhammet Parlak edited this page Feb 8, 2018 · 3 revisions

This page demonstrates how to quickly get started in creating and evaluating expressions.

// Define the context of our expression
ExpressionContext context = new ExpressionContext();
// Allow the expression to use all static public methods of System.Math
context.Imports.AddType(typeof(Math));

// Define an int variable
context.Variables["a"] = 100;

// Create a dynamic expression that evaluates to an Object
IDynamicExpression eDynamic = context.CompileDynamic("sqrt(a) + pi");
// Create a generic expression that evaluates to a double
IGenericExpression<double> eGeneric = context.CompileGeneric<double>("sqrt(a) + pi");

// Evaluate the expressions
double result = (double)eDynamic.Evaluate();
result = eGeneric.Evaluate();

// Update the value of our variable
context.Variables["a"] = 144;
// Evaluate again to get the updated result
result = eGeneric.Evaluate();

The ExpressionContext holds all the information required for an expression (besides the expression text). We use its Imports property to make all the static members of the System.Math class available to the expression and the Variables property to dynamically define some variables. With the context defined, we compile the expression text to create a dynamic expression (evaluates to Object) or a generic expression (type-safe and fast) and finally call the Evaluate method on either expression to get its result.

Invalid expressions

Expressions can fail to compile if, for example, the syntax of the text is invalid. An ExpressionCompileExpression will be thrown whenever an expression cannot be compiled.

try
{
   ExpressionContext context = new ExpressionContext();
   IDynamicExpression e = context.CompileDynamic("100 +* 200");
}
catch (ExpressionCompileException ex)
{
   // Handle expression compile error
   if (ex.Reason == CompileExceptionReason.SyntaxError)
      Console.WriteLine("Check your expression syntax");
}