Question

Let's use this method that I'm trying to call as an example:

 MyMethod<MyType, string>(Expression<Func<MyType, string>> expression)

If I try to dynamically build the following expression x => x.Name and pass it to the method, everything works just fine:

var pi = typeof(MyType).GetProperty("Name");
ParameterExpression pe = Expression.Parameter(typeof(MyType), "x");
MemberExpression me = Expression.Property(pe, pi);
var exp = Expression.Lambda(me, pe);

Now let's imagine that in the exact same scope, I'm trying to build this expression instead x => item.Name using the following code, obviously item being different than the input parameter x:

var item = new MyType() { Name = "My name" };
var pi = t.GetProperty("Name");
ParameterExpression pe = Expression.Parameter(typeof(MyType), "x");
ParameterExpression pe2 = Expression.Parameter(typeof(MyType), "item");
MemberExpression me = Expression.Property(pe2, pi);
var exp = Expression.Lambda(me, pe);

When I try to call MyMethod I get the following error, probably because there's no variable "item" in the scope where MyMethod is called (which is not where I build the expression):

variable 'item' of type 'MyType' referenced from scope '', but it is not defined

How can I build this expression in such a way that it won't throw this error?

Was it helpful?

Solution

Within the scope of the lambda, the item bit is a constant - it's not a variable parameter to the invocation.

So the following should be closer:

var item = new MyType() { Name = "My name" };
var pi = t.GetProperty("Name");
ParameterExpression pe = Expression.Parameter(typeof(MyType), "x");
ConstantExpression ce = Expression.Constant(typeof(MyType), item);
MemberExpression me = Expression.Property(ce, pi);
var exp = Expression.Lambda(me, pe);

OTHER TIPS

The string "item" is not related in any way to the local variable item. If you want your constructed lambda expression to capture the value of the local variable item, then instead of Expression.Parameter(typeof(MyType), "item") you need Expression.Constant(item).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top