Stuck with BinaryExpression in C#

Go To


I want to implement

Expression<Func<int, int, int>> Max = (p1,p2) => p1 > p2 ? p1:p2;

as an expression tree and tried

ParameterExpression LeftEx = Expression.Parameter(typeof(int), "p1");
ParameterExpression RightEx = Expression.Parameter(typeof(int), "p2");
BinaryExpression GroesserAls =  Expression.GreaterThan(LeftEx, RightEx);
ConditionalExpression Cond = BinaryExpression.Condition(GroesserAls, LeftEx, RightEx);
Expression main = Cond.Test;
Expression<Func<int, int, bool>> Lam = Expression.Lambda<Func<int, int, bool>>(main,
  new ParameterExpression[] { LeftEx, RightEx });
Console.WriteLine(Lam.Compile().Invoke(333, 1200));

With Cond I either get true/false but not the LeftEx or RightEx that Condition should return.

I couldn't find anything in the documentation.


2009-06-16 09:33
by Pemo12
Don't forget, you can always use reflector or ildasm to see what expression tree code the compiler generates for you - Eric Lippert 2009-06-16 15:18


I think you just need:

Expression<Func<int, int, int>> Lam =
    Expression.Lambda<Func<int, int, int>>(Cond, // <=== HERE
        new ParameterExpression[] { LeftEx, RightEx });

edit - btw - var is your friend here:

    var p1 = Expression.Parameter(typeof(int), "p1");
    var p2 = Expression.Parameter(typeof(int), "p2");
    var body = Expression.Condition(Expression.GreaterThan(p1, p2), p1, p2);
    var lambda = Expression.Lambda<Func<int, int, int>>(body, p1, p2);
    var func = lambda.Compile();
2009-06-16 09:37
by Marc Gravell
I think the Func return type should be int (Func - bruno conde 2009-06-16 09:40
(fixed, cheers - Marc Gravell 2009-06-16 09:40