.NET 4.0 SPECIFICS

As mentioned earlier, .NET 4.0 has extended the supported language elements for expression trees, but the C# language hasn’t seen any corresponding extensions yet. As a result, expression trees can currently be constructed through helper functions of the Expression class in .NET 4.0, which don’t have a syntactic representation in the language itself. It’s possible to implement a function or a lambda expression with the same functionality as any given expression tree, but the automatic conversion into an expression tree doesn’t work.

For instance, here is a simple function to calculate a factorial using an iterative algorithm:

static int Fact(int x) {

  int result = 1;

  for (int m = 2; m <= x; m++)

    result *= m;

  return result;

}

As a lambda expression, this is what the function looks like:

Func<int, int> fact = x => {

  int result = 1;

  for (int m = 2; m <= x; m++)

    result *= m;

  return result;

};

But that is not possible and results in the compilation error “A lambda expression with a statement body cannot be converted to an expression tree.”

Expression<Func<int, int>> factExpression = x => {

  int result = 1;

  for (int m = 2; m <= x; m++)

    result *= m;

  return result;

};

Constructing the expression tree for this simple algorithm is quite complicated. Here’s the function that does it:

static Func<int, int> ConstructRuntimeFact( ) {

  var param = Expression.Parameter(typeof(int), "x");

  var resultVar = Expression.Variable(typeof(int), "result"); ...

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.