Skip to content

Expression Compiler

Akash Kava edited this page Dec 23, 2022 · 3 revisions

Getting Started

All expressions are prefixed with Y, and can be constructed easily as shown below.

var a = YExpression.Parameter(typeof(int));
var b = YExpression.Parameter(typeof(int));

var exp = YExpression.Lambda<Func<int,int,int>>("add",
            YExpression.Binary(a, YOperator.Add, b),
            new YParameterExpression[] { a, b });

var fx = exp.Compile();

Assert.AreEqual(1, fx(1, 0));
Assert.AreEqual(3, fx(1, 2));



This method will compile expression to IL in memory, it will not analyze nested lambdas, this is by design to generate IL faster. For nested lambda, please use CompileWithNestedLambdas method. It will return DynamicMethod delegate.


When you expression tree contains nested lambda with closures, use this method to generate the IL. It will return DynamicMethod delegate.


This is similar to CompileToMethod, this method generate an empty assembly and it will return generated method from MethodBuilder.


This is same as CompileToMethod of Linq.


You can compile lambda with this parameter to an instance method.

For More,

No Validation

API is similar to that of SLE, but implementation is faster as it does not perform any checks whether the expression is correct or not. There are no null checks either. Since we needed to speed up the code generation, we had to skip various checks.

So in order to use the library, you must validate your expressions with SLE and then you can easily replace it with Yantra Expressions.

Following validations are not performed

  1. Label must be within correct block, SLE checks if jumps are possible in blocks. Jumps out of try/catch are not permitted etc.
  2. Return/Jump not permitted in finally block.
  3. Argument types mismatch, SLE checks each method's input output type with expressions.
  4. Nullable conversion, for example if you pass int to int? or int? to int it will result in Common Language Runtime Error. As IL is generated as it is. Executing such IL will result in error.

There may be more validations, and we do not plan to add them.

Reason being, we are using this to generate JavaScript IL code, however all these validations are already performed and translated correctly by JavaScript parser and compiler. And there are thousands of unit test of JavaScript which tells us that Expression Compiler is generating code correctly.