The MSDN documentation states:
Expression.Quote
Method Creates a UnaryExpression that represents an expression that has a constant value of type Expression.
I've been able to build predicate expressions for use in LINQ queries by manually constructing them using the Expression class, but have never come across the need for Expression.Quote.
When and why would you use this? From the LINQ expressions I've seen that have them, they just seem to wrap existing expressions without adding any value.
What is the purpose of the Quote method/node type?
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
usingExpression.Call
, any parameters that are lambda expressions (LambdaExpression
/Expression<TDelegate>
) must useExpression.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'sType
property would beFunc<bool>
whereas the expression's type (callingGetType
) would beExpression<Func<bool>>
So to get an
Expression
that has the correct value for theType
property you pass the lambda expression intoExpression.Quote
and pass that as the parameter toExpression.Call
.I had a look at
Expression.Quote
through reflector and while the sole parameter is of typeExpression
, it must derive fromLambdaExpression
and this is checked inside the method. Out of interest, anyone know why MS didn't just make the parameter type beLambdaExpression
?As StevenH pointed out,
Expression.Quote
is used in implementing LINQ Query Providers. All the methods onQueryable
that take a lambda expression such asWhere
,OrderBy
,GroupBy
, etc internally construct aMethodCallExpression
usingExpression.Call
and wrap the lambda expression parameters withExpression.Quote
calls.For a more detailed explanation of
Expression.Quote
read this answer.