Dmitriy Shapar
Dmitriy Shapar

Reputation: 138

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

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)

Upvotes: 6

Views: 3517

Answers (1)

usr
usr

Reputation: 171178

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.

Upvotes: 9

Related Questions