Expressions: variable referenced by scope, but no exception defined

I am new to System.Linq.Expresions and I am trying to figure out what is 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 just want to create something like mc.Val = 5, assuming MyClass and the object parameter are lambda parameters (I don't want to use closure)

+4
source share
1 answer

e.Body refers to a parameter from e . But this is a different parameter than xParam . It is not enough that both have the same name. They must be the same object.

In understanding, you are trying to get expressions using lambdas as a tool to create them. For this approach to work, you need to replace all the parameters in e with the parameters that you control ( xParam ). You must be consistent.

+7
source

All Articles