Creating a Func<> dynamically - Lambdas vs. Expression trees
.net, c#, c#-4.0, expression-trees, lambda
Solution
If you know the code at compile-time, I'd almost certainly use a lambda expression. The fact that the parameters are captured (rather than being expressed as constants) is almost always going to be irrelevant - and in order to justify building an expression tree, you'd have to prove that it was significant.
Expression trees are much more applicable when:
- You want to build them dynamically from different bits of expressions
- You want to analyze the expression tree as data, e.g. as a LINQ provider
When those aren't the case, the readability benefit of using a lambda expression is massive.
Problem
Here is some code to return a linear function (y=ax+b). ``` public static Func<double, double> LinearFunc(double slope, double offset) { return d => d * slope + offset; } ``` I could do the same thing with expression trees, but I'm not sure it is worth the effort. I know that the lambda will capture the parameters, which is a downside. Are there any more pros/cons which I'm not aware of? My main question is, is it worth it to use expression trees in this scenario? Why or why not?