EXPRESSION TREES IN .NET

Since version 3.5, .NET as well as Microsoft’s .NET languages have had support for expression trees. These support a form of an eval mechanism for a particular restricted subset of the languages. Some additional major steps have been made in .NET 4.0, triggered by the Dynamic Language Runtime (DLR) development, but these are unfortunately not supported by the C# language in version 4.0 — apparently the C# team felt that there was work left to do on expression tree support, and that an extension of the existing language support would be incomplete and potentially confusing at this time.

Consider this simple lambda expression:

Func<int, int, int> add = (x, y) => x + y;

As you know by now, this results in a local function, which you can call in order to add two int values:

int result = add(10, 20);

// result is now 30

The lambda expression is compiled code. The anonymous function is translated into IL code during the C# compiler run. To create an expression tree instead, the syntax has to be modified a little:

Expression<Func<int, int, int>> addExpr =

  (x, y) => x + y;

The only difference is the type of the variable that holds the lambda expression. This difference instructs the C# compiler to create entirely different code. Instead of compiling the code to perform the addition operation into IL, the compiler generates code to create a complex hierarchy of objects, all of which are of types derived from System.Linq.Expressions.Expression.

Because the ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.