Search code examples
c#linqexpression-treesiqueryable

What makes the C# compiler output an expression tree instead of code?


Here is the code.

  int[] data = new int[] { 1, 2, 3, 4, 5 };
  var q1 = data.Select(x => 10 * x);
  var q2 = data.AsQueryable().Select(x => 10 * x);
  Expression<Func<int,int>> qe = (x) => 10 * x;

In the first case the compiler generates code to evaluate the expression. There is no expression tree in the output.

In the second it generates an expression tree (visible on debug), which at run-time is compiled and executed to perform the query (and does exactly the same thing).

In the third case, the same lambda as (2) is created directly as an expression tree (not as code).

What makes the compiler generate an expression tree instead of code in these two cases, and are there any other interesting cases?

The reason: I want to 'pick apart' the top level of the expression tree at runtime, and then compile and execute the lower levels. I'm having trouble getting the compiler to do things my way!


Solution

  • Enumerable's Select method accepts a parameter of type Func<TSource,TResult>. Queryable's Select method accepts a parameter of type Expression<Func<TSource,TResult>>.

    It's as simple as that - if the compiler has a lambda expression it can either generate an expression or compile the lambda, and that decision is based on what it's being asked to create - if it's an Expression of some type, it will generate the expression tree. If it's a Func or other delegate type, it generates the code.