Table of Contents

Lambda Compilation

Using the concept of lambda compilation, NCalc can convert a LogicalExpression object to an anonymous function. Using this you can write complex functions and even have greater performance when evaluating the expression.

Especial thanks to the NCalc2 fork for the original implementation.

Functionalities

Simple Expressions

var expression = new Expression("1 + 2");
Func<int> function = expression.ToLambda<int>();
Debug.Assert(function()); //3

Expressions with Functions and Parameters

class Context
{
  public int Param1 { get; set; }
  public string Param2 { get; set; }
  
  public int Foo(int a, int b)
  {
    return a + b;
  }
}

var expression = new Expression("Foo([Param1], 2) = 4 && [Param2] = 'test'");
Func<Context, bool> function = expression.ToLambda<Context, bool>();

var context = new Context { Param1 = 2, Param2 = "test" };
Debug.Assert(function(context)); //true

Performance

You should cache the result of <xref:NCalc.Expression.ToLambda`1>. The evaluation is indeed faster, but the compilation of the lambda is very slow. See benchmarks for more info.