Expression.Quote
specifies that a lambda is to be treated as an expression tree and not as a function. It induces closure semantics on its operand.
When you are constructing a MethodCallExpression
using Expression.Call
, any parameters that are lambda expressions (LambdaExpression
/Expression<TDelegate>
) must use Expression.Quote
to wrap the parameter before passing in.
So for a parameter of type Expression<Func<bool>>
, when you create an instance such as: () => true
, the expression's Type
property would be Func<bool>
whereas the expression's type (calling GetType
) would be Expression<Func<bool>>
So to get an Expression
that has the correct value for the Type
property you pass the lambda expression into Expression.Quote
and pass that as the parameter to Expression.Call
.
I had a look at Expression.Quote
through reflector and while the sole parameter is of type Expression
, it must derive from LambdaExpression
and this is checked inside the method. Out of interest, anyone know why MS didn't just make the parameter type be LambdaExpression
?
As StevenH pointed out, Expression.Quote
is used in implementing LINQ Query Providers. All the methods on Queryable
that take a lambda expression such as Where
, OrderBy
, GroupBy
, etc internally construct a MethodCallExpression
using Expression.Call
and wrap the lambda expression parameters with Expression.Quote
calls.
For a more detailed explanation of Expression.Quote
read this answer.
Func<>
, then sure that is all you need, but in the case of many LINQIQueryable<T>
extension methods, the parameter type is actuallyExpression<Func<>>
, and in that case you will needExpression.Quote
. I haven't tried doing this with .NET 4.5, but I'd assume it was the same. At the time of writing I was probably using .NET 3.5. – Fujio