return Expression based on Expression.IfThenElse

Nov 24, 2009 at 4:35 PM

Is it possible to return an Expression.Constant(1) or Expression.Constant(0) depending on the result of an Expression.IfThenElse?

My language spec requires comparison operators to return 1 when true, and 0 when false.

print (1<2)==1 //this should print "1"

I looked in the ExpressionTree/UESamples solution and I rummaged around in the Ruby and Python code. If it is in there I wasn't looking in the right places.

I've been trying something like the code below. Not sure if I just need to tweek it.

I've also be writing incorrect code using Expression.Return. Not sure if I'm heading down the wrong path or not.

 

 

internal static Expression LessThan(Expression left, Expression right)
        {
            //return Expression.Lambda<Func<int>>(Expression.Block(
            //    BlockExpression.IfThenElse(
            //        Expression.LessThan(left, right),
            //        Expression.Constant(1),
            //        Expression.Constant(0)
            //    )));

            return Expression.Block(
                Expression.IfThenElse(
                    Expression.LessThan(left, right),
                    Expression.Constant(1),
                    Expression.Constant(0)
                ));
            
        }

 

 

Nov 24, 2009 at 5:35 PM

It seems a ConditionalExpression should work for you:

return Expression.Condition(
                    Expression.LessThan(left, right),
                    Expression.Constant(1),
                    Expression.Constant(0)
                );

Nov 24, 2009 at 6:20 PM

wow... not sure how i missed that class. works great.