tags:

views:

269

answers:

4

As an example, why do most LINQ operators accept Expression<Func<TSource>> and it's equivalent Func<TSource>

What's the benefit/reason for using the generic Expression class instead of straight up lamda syntax?

+10  A: 

Using Expression<T> you are explicitly creating an expression tree - this means that you can deal with the code that makes up the query as if it were data.

The reason for this is that LINQ providers (like LINQ to SQL for example) inspect the query itself to determine the best way to translate the C# expressions into a T-SQL query. Since an expression tree lets you look at the code as data the provider is able to do this.

Andrew Hare
Don't forget that Expression Trees are not exclusive to LINQ providers anymore - for example, they're one of the main underlying concepts of the Dynamic Language Runtime.
DrJokepu
@DrJokepu - Good point!
Andrew Hare
+1  A: 

Func<T> creates an executable function.

Expression<Func<T>> creates an expression tree that allows you to work with the code in the function as data.

Expression Trees allow you to do things like LINQ to SQL and LINQ to XML by generating the underlying calls from your .NET code.

Justin Niessner
+1  A: 

An Expression<Func<>> is the representation of a function that has yet to be turned into code. A Func<> is an actual executable function. Using the former allows you to turn the expression into the appropriate function at the time that it is invoked. For example, with LINQ to SQL this will translate it into a the equivalent code to execute a SQL statement and return the specified contents. With LINQ to objects, it will execute code on the client using the CLR. A Func<> is always executed in the CLR -- it's executable code.

tvanfosson
+3  A: 

In summary, the key differences between the two are following:

  • Expression<Func<...>> is an expression tree which represents the original source code (it is stored in a tree-like data structure that is very close to the original C# code). In this form, you can analyze the source code and tools like LINQ to SQL can translate the expression tree (source code) to other languages (e.g. SQL in case of LINQ to SQL, but you could also target e.g. JavaScript).

  • Func<...> is an ordinary delegate that you can execute. In this case, the compiler sompiles the body of the function to intermediate language (IL) just like when compiling standard method.

It is worth mentioning that Expression<..> has a Compile method that compiles the expression at run-time and generates Func<...>, so there is conversion from the first one to the second one (with some performance cost). However, there is no conversion from the second one to the first one, because once you get IL, it is very difficult (impossible) to reconstruct the original source code.

Tomas Petricek