Create Func from MemberExpression and Constant

.net c# expression expression-trees lambda

Question

I don't do expression tree work enough to get this working...

Essentially what I want to create is m.MyProperty == 1, to be used in a method that takes Func<T, bool>.

I have a MemberExpression already. I've tried various things, but I just keep getting different errors.

I currently have something like this (that doesn't work):

object const = 1;
var equalExpression = Expression.Equal( memberExpression, Expression.Constant( const ) );
var compiled = Expression.Lambda<Func<T, bool>>( equalExpression, Expression.Parameter( typeof( T ) ).Compile();

This gives me an exception:

System.InvalidOperationException: variable 'm' of type 'MyType' referenced from scope '', but it is not defined

I've tried re-working several different parts of this but haven't come up with anything that works.

The const is an object that can be any type, but should match the type of the MemberExpression.

Solution:

object c = 1;
var parameterExpression = (ParameterExpression)memberExpression.Expression;
var equalExpression = Expression.Equal(memberExpression, Expression.Constant(c));
var compiled = Expression.Lambda<Func<T, bool>>(equalExpression, parameterExpression).Compile();

Accepted Answer

The reason this does not work is that you are using a "free-standing" parameter expression when compiling your lambda. You should create Expression.Parameter( typeof( T )) before making your memberExpression, and use the same instance of ParameterExpression both when you make a member expression and when you are compiling the lambda:

var pe = Expression.Parameter( typeof( T )); // <<== Here
var memberExpression = Expression.PropertyOrField(pe /* Here */, "MyProperty");
var equalExpression = Expression.Equal( memberExpression, Expression.Constant( const ) );
var compiled = Expression.Lambda<Func<T, bool>>( equalExpression, pe ).Compile();
//                                                                ^^
//                                                                ||
//                                                             And here


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