I understand lambdas and the Func and Action delegates. But expressions stump me.
In what circumstances would you use an Expression<Func<T>> rather than a plain old Func<T>?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When you want to treat lambda expressions as expression trees and look inside them instead of executing them. For example, LINQ to SQL gets the expression and converts it to the equivalent SQL statement and submits it to server (rather than executing the lambda).
Conceptually,
Expression<Func<T>>is completely different fromFunc<T>.Func<T>denotes adelegatewhich is pretty much a pointer to a method andExpression<Func<T>>denotes a tree data structure for a lambda expression. This tree structure describes what a lambda expression does rather than doing the actual thing. It basically holds data about the composition of expressions, variables, method calls, … (for example it holds information such as this lambda is some constant + some parameter). You can use this description to convert it to an actual method (withExpression.Compile) or do other stuff (like the LINQ to SQL example) with it. The act of treating lambdas as anonymous methods and expression trees is purely a compile time thing.will effectively compile to an IL method that gets nothing and returns 10.
will be converted to a data structure that describes an expression that gets no parameters and returns the value 10:
While they both look the same at compile time, what the compiler generates is totally different.