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>
?
views:
1056answers:
3You would use an expression when you want to treat your function as data and not as code. You can do this if you want to manipulate the code (as data). Most of the time if you don't see a need for expressions then you probably don't need to use one.
LINQ is the canonical example (for example, talking to a database), but in truth, any time you care more about expressing what to do, rather than actually doing it. For example, I use this approach in the RPC stack of protobuf-net (to avoid code-generation etc) - so you call a method with:
string result = client.Invoke(svc => svc.SomeMethod(arg1, arg2, ...));
This deconstructs the expression tree to resolve SomeMethod
(and the value of each argument), performs the RPC call, updates any ref
/out
args, and returns the result from the remote call. This is only possible via the expression tree. I cover this more here.
Another example is when you are building the expression trees manually for the purpose of compiling to a lambda, as done by the generic operators code.