Darkhan Zholmukhanov
Darkhan Zholmukhanov

Reputation: 76

ExpressionTree. Using Lambda Expressions in Binary Expressions

Is there any way to use lambdas in binary expressions (like Add, Subtract, etc) as arguments.

        Expression<Func<double>> foo = () => 5.5;
        Expression<Func<double>> bar = () => 10.5;
        Expression<Func<double>> res = Expression.Lambda<Func<double>>(Expression.Add(bar, foo));
        Console.WriteLine(res.Compile()());

This throws System.InvalidOperationException: The binary operator Add is not defined for the types 'System.Func1[System.Double]' and 'System.Func1[System.Double]'.

I'm aware of ConstantExpression. I just want to call lambdas and use the result in arithmetic calculations. Is this even achievable? I'm clearly missing some of the fundamentals on how Expression Trees are implemented.

EDIT: I found out that similar thing can be achieved by using MethodCallExpression in arguments instead of Expression<Func<double>>. But the question remains relevant.

Upvotes: 0

Views: 319

Answers (1)

JyothiJ
JyothiJ

Reputation: 315

Replace the Add line to following

var res = Expression.Lambda<Func<double>>(Expression.Add(bar.Body, foo.Body));

it will work.

Upvotes: 2

Related Questions