Reputation: 5941
Shouldn't that return 6 instead of 8 ? Doesn't it work this way that using combination of expressions it returns one big expression and this should evaluate as 2+2*2
instaed (2+2)*2
static void Main(string[] args)
{
var response = Mul();
var result = response.Compile().Invoke();
}
public static Expression<Func<double>> Add()
{
return Expression.Lambda<Func<double>>(Expression.Add(EvaluateConst().Body, EvaluateConst().Body));
}
public static Expression<Func<double>> Mul()
{
return Expression.Lambda<Func<double>>(Expression.Multiply(EvaluateConst().Body, Add().Body));
}
public static Expression<Func<double>> EvaluateConst()
{
return () => 2;
}
Upvotes: 0
Views: 364
Reputation: 10718
You're passing around operators as arguments to the functions. While the compiler can see 2+2*2
and make the jump to Add(2, Multiply(2, 2))
, expressions do not. An easy way to see this is to think (or rather, realize, since it's true) that operators are static functions, or replace your operator expressions with Method Call Expressions.
Upvotes: 1
Reputation: 203838
No, it should not. If it should have, it would have. Your instructions are to multiply 2 with the results of the addition, because you pass 2 and the results of the addition as the operations to the multiplication.
Upvotes: 3
Reputation: 61379
A return value of "8" makes sense here.
Before Expression.Multiply
can be run, its arguments must be fully determined. So each function is run.
And 2 * 4 is 8.
Upvotes: 4