LambdaExpression Variable Referenced From Scope But Not Defined

c# expression-trees

Question

I have a simple lambda expression that I would like to compile and invoke

Expression< Func< Commands, bool>> expression = c => c.IsValid("test");

but when I do the following:

LambdaExpression le = Expression.Lambda(expression.Body);

object result = le.Compile().DynamicInvoke();

the compile throws the error:

variable 'c' of type 'ConsoleApplication1.Commands' referenced from scope '', but it is not defined

How do you set the instance variable for this expression?

Popular Answer

Why not just compile the expression itself? If you'd like to invoke it with some specific 'ConsoleApplication1.Commands' instance multiple times you could then just close over that instance:


var validator = expression.Compile();

var c = new Commands();
var validatorForC = () => validator(c);

Otherwise you'll need to build call expression, like this:


var c = new Commands();
var le = Expression.Lambda(Expression.Invoke(expression, Expression.Constant(c)));
object result = le.Compile().DynamicInvoke();

or you can make ExpressionVisitor which will replace all occurences of the 'c' parameter in 'expression.Body' with Expression.Constant.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why