Difference between Expression<Func<>> and Func<> [duplicate]
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.
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.