Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Expression<Func<>> and Func<> [duplicate]

Tags:

c#

linq

As an example, why do most LINQ operators accept Expression<Func<TSource>> and its equivalent Func<TSource>?

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

like image 587
Razor Avatar asked Apr 19 '10 01:04

Razor


2 Answers

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.

like image 166
Andrew Hare Avatar answered Oct 06 '22 23:10

Andrew Hare


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 compiles 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.

like image 44
Tomas Petricek Avatar answered Oct 06 '22 23:10

Tomas Petricek