Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Func<> dynamically - Lambdas vs. Expression trees

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?

like image 975
Kendall Frey Avatar asked May 26 '12 15:05

Kendall Frey


1 Answers

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.

like image 187
Jon Skeet Avatar answered Nov 07 '22 16:11

Jon Skeet