Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between Expression and Func

Tags:

c#

What is the difference between Expression and Func? The same task can be attained by both. So what is the difference?

like image 305
developer Avatar asked Jun 26 '10 08:06

developer


1 Answers

Expression trees are data representations of logic - which means they can be examined at execution time by things like LINQ providers. They can work out what the code means, and possibly convert it into another form, such as SQL.

The Func family of types, however, are just delegates. They end up as normal IL, which can be executed directly, but not (easily) examined. Note that you can compile expression trees (well, Expression<T> and LambdaExpression) into delegates and execute those within managed code as well, if you need to.

You can build up expression trees manually using the factory methods in the Expression class, but usually you just use the fact that C# can convert lambda expressions into both expression trees and normal delegates:

Expression<Func<int, int>> square = x => x * x;
Func<int, int> square = x => x * x;

Note that there are limitations on which lambda expressions can be converted into expression trees. Most importantly, only lambdas consisting of a single expression (rather than a statement body) can be converted:

// Compile-time error
Expression<Func<int, int>> square = x => { return x * x; };
// Works fine
Func<int, int> square = x => { return x * x; };
like image 121
Jon Skeet Avatar answered Oct 16 '22 10:10

Jon Skeet