Search code examples
c#expression-trees

How to return value in ExpressionTree


i'm trying to do for an expression tree and try to let it return a simple int value. but it not working anymore

        var method = typeof(Console).GetMethod("WriteLine", new Type[] {typeof(string)});

        var result = Expression.Variable(typeof(int));



        var block = Expression.Block(
            result,
          Expression.Assign(result,Expression.Constant(0)),
            Expression.IfThenElse(Expression.Constant(true),
                Expression.Block(Expression.Call(null, method, Expression.Constant("True")),
                    Expression.Assign(result, Expression.Constant(1))),
                Expression.Block(Expression.Call(null, method, Expression.Constant("False")), Expression.Assign(
                    result, Expression.Constant(0)
                ))),
            result
        );


        Expression.Lambda<Func<int>>(block).Compile()();

Solution

  • The problem is not with returning a vaue from the block (you are doing it correctly), but the out of scope variable due to the used wrong Expression.Block method overload.

    Variable expressions like your result must be passed to the block expression using some of the overloads with IEnumerable<ParameterExpression> variables argument, for instance

        var block = Expression.Block(
            new ParameterExpression[] { result },
            //... (the rest of the sample code unchanged)
        );