GENERATING EXPRESSIONS

Making the step from analyzing expressions to constructing them isn’t difficult. With the help of the ExpressionDumper and the support of the C# compiler (as far as it currently goes), it’s easy to find out how common expressions are represented in the trees. The Expression class has a lot of helper functions that make it easy to construct new expression trees at runtime. These can then be used in any APIs that use function passing (by compiling the expression trees) or in those that use the expression trees directly (like LINQ). This can be a modern form of dynamic querying, using expression trees as an intermediate step and thereby increasing flexibility, security, and type safety.

Here’s the expression tree again for the add function:

LambdaExpression (

  Parameters:

    ParameterExpression (x)

    ParameterExpression (y)

  Body:

    BinaryExpression:Add (

      Left:

        ParameterExpression (x)

      Right:

        ParameterExpression (y)

    )

)

Such a tree makes it easy to see the elements that are being used, and with the helper functions in the Expression class it’s just as easy to construct the same tree. Here’s the code for this function:

ParameterExpression xParam = Expression.Parameter(typeof(int), "x");

ParameterExpression yParam = Expression.Parameter(typeof(int), "y");

 

var addExpr = Expression.Lambda<Func<int, int, int>>(

  Expression.Add(xParam, yParam), xParam, yParam);

Starting from the innermost element, Expression.Add is used ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.