German
German

Reputation: 740

Is there a way to compile a lambda expression passing an object generated run time?

I need to compile a lambda expression passing an object generated run time. Here is code I have so far.

An example:

var anonType = new { Name = "Florida" }.GetType();
var myObj = Activator.CreateInstance(anonType, "Florida");

var expression = Expression.Parameter(myObj.GetType(), "Name");
var property = Expression.Property(expression, "Name");

var rule = new Rule("Name", "NotEqual", "Florida");

ExpressionType tBinary;

if (!Enum.TryParse(rule.Operator, out tBinary)) return;
var propertyType = myObj.GetType().GetProperty(rule.MemberName).PropertyType;
var right = Expression.Constant(Convert.ChangeType(rule.TargetValue, propertyType));
var result = Expression.MakeBinary(tBinary, property, right);

var expr = Expression.Lambda<Func<Type, bool>>(result, expression).Compile();
var isValid = expr(anonType);

I'm getting an error at the line when its trying to compile Lambda expression.

Additional information: ParameterExpression of type '<>f__AnonymousType0`1[System.String]' cannot be used for delegate parameter of type 'System.Type'

Upvotes: 1

Views: 110

Answers (1)

Evk
Evk

Reputation: 101483

Not sure what you want to achieve with that, but will answer your direct question. You can compile lambda like this in your case:

// create Func<AnonymousType, bool>
var func = typeof(Func<,>).MakeGenericType(anonType,typeof(bool));            
// compile
var expr = Expression.Lambda(func, result, expression).Compile();
// invoke
var isValid = expr.DynamicInvoke(new { Name = "NotFlorida" });

Upvotes: 2

Related Questions