Search code examples
c#.net-4.0lambdaexpression-trees

Expression Trees reuse Values?


Im reading Jon Skeet book. ( Expression Trees Chapter) It has an example of creating expression tree out of lambda Expressions :

Expression<Func<string, string, bool>> expression =    (x, y) => x.StartsWith(y);
var compiled = expression.Compile();
Console.WriteLine(compiled("First", "Second"));
Console.WriteLine(compiled("First", "Fir"));

Now he is doing the same with expression tree :

enter image description here

question :

The yellow part already includes the params info !

why Do I have to specify AGAIN in the blue part those param ?


Solution

  • I think your question is:

    Why can't Expression.Lambda inspect the entire expression-body for parameter-expressions and then use them as the expression-parameters, relieving me of the trouble of having to explicitly hand them over again in the Lambda call?

    Well, it certainly could, but how would it know in what order to accept those parameters in the general case?

    In your example, how would it know whether to generate the expression-equivalent of:

    (x, y) => x.StartsWith(y) 
    

    (or)

    (y, x) => x.StartsWith(y)?
    

    Should your lambda.Compile()("42", "4") return true or false?

    It can't make these decisions on your behalf in the general case.