Expressions: Variable referenced from scope, but it is not defined exception
Asked Answered
S

1

6

I'm pretty new in System.Linq.Expresions, and I'm trying to figure out what wrong with this code:

 var mc = new MyClass();

        ParameterExpression value = Expression.Parameter(typeof(object), "value");
        ParameterExpression xParam = Expression.Parameter(typeof(MyClass), "x");

        Expression<Func<MyClass, object>> e = x => x.Val;

        BlockExpression block = Expression.Block(new[] { xParam, value },
            Expression.Assign(e.Body, value));

        Expression.Lambda<Action<MyClass, object>>(block, xParam, value).Compile()(mc, 5); //I'm getting exception here when Compile()

...

class MyClass
    {
        public object Val
        {
            get;
            set;
        }
        public object OtherVal
        {
            get;
            set;
        }
    }

I'm just want to build something like mc.Val = 5 assuming that MyClass and object parameter is the parameters of lambda (I don't want to use closures)

Sunbreak answered 3/12, 2012 at 19:56 Comment(1)
People generally appreciate it when you post the full error message and stack traceTurnbuckle
P
9

e.Body references a parameter from e. But that is a different parameter than xParam. It is not enough that the two have the same names. They must be the same object.

In understand you try to obtain expressions using lambdas as a tool to generate them. For that approach to work you need to replace all parameters in e with parameters that you control (xParam). You have to be consistent.

Phenobarbital answered 3/12, 2012 at 20:0 Comment(2)
In other words, if you create a lambda expression and then use passed parameters inside that lambda expression (i.e. in a block expression or call expression) - you need to use the same ParameterExpression objects when constructing different expression objects (LambdaExpression and inner expression).Richman
@Richman that is correct. If architecture demands it you can also rewrite an existing expression tree and replace parameter expressions to your liking.Phenobarbital

© 2022 - 2024 — McMap. All rights reserved.