Reputation: 549
I need to preface this question with statement that I'm a noob when it comes to dynamic expressions.
We have some existing code that looks through an object, and then retrieves a property value for that object using a dynamic expression:
var lambda = System.Linq.Dynamic.DynamicExpression.ParseLambda(instance.GetType(), typeof(object), newExpression.Trim());
var result = lambda.Compile().DynamicInvoke(instance);
I'm wondering if it's possible to instead SET a value for the property? This is retrieving a result(which is actually the result of the expression which is the property value) but I want to instead set a property value instead. Not sure I'm barking up the completely wrong tree here.
Upvotes: 0
Views: 2694
Reputation: 526
You're really close there - just need to go with the following:
var param = Expression.Parameter(typeof(T), "instance");
var lambda = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { param }, typeof(object), newExpression.Trim());
var assign = Expression.Lambda<Action<T>>(Expression.Assign(Expression.Property(param, "Property"), lambda.Body)), param);
assign.Compile().Invoke(instance);
Probably you need to fiddle with the types a bit, you can remove the generic from the Lambda and DynamicInvoke rather than Invoke. I'm doing this strongly typed in a generic object that I created with MakeGenericType, GetConstructor, etc.
Upvotes: 0