Question

How can i do pass parameters to an expression tree as collection? For example Expression.Block(params Expression[] expressions) expects parameters as array. So can i create a List collection and pass parameters with this.

for example i translated this code to expression tree

void func(int p1)
{
    int i;
    i = 0;
    for (; i < p1; i++)
    {
        Console.WriteLine("Hello World");
    }
}

to 

 ParameterExpression i = Expression.Parameter(typeof(int), "i");
        ParameterExpression p1 = Expression.Parameter(typeof(int), "p1");
        LabelTarget label = Expression.Label();

        List<Expression> lines = new List<Expression>();
        lines.Add(i);//this is local variable "i" that i declared above
        lines.Add(Expression.Assign(i, Expression.Constant(0)));
        lines.Add(Expression.Loop(
            Expression.Block(
            Expression.IfThenElse(Expression.LessThan(i, p1), Expression.Assign(i, Expression.Add(i, Expression.Constant(1))), Expression.Break(label)),
                Expression.Call(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }), Expression.Constant("Hello World"))
            ), label
            ));

        BlockExpression block = Expression.Block(
            lines.ToArray()
            );

        Expression.Lambda<Action<int>>(block, new ParameterExpression[] { p1 }).Compile()(10);

this code compiles but when i run it I get

"UnhandledException:System.InvalidOperationException: variable 'i' of type 'System.Int32' referenced from scope '', but it is not defined"

But i defined "i" with => lines.Add(i); What is wrong here?

How can i add list.Add(A local variable) or is there anyway adding Expression to Block in RunTime like Block.add?

Was it helpful?

Solution

When you declare the block, you need to pass any variables referenced with in the block as the first argument,

BlockExpression block = Expression.Block(
    new ParameterExpression[] { i },
    lines.ToArray()
    );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top