What I am trying to do seems simple, but I can't find a way. Let's suppose I have a method with this signature:
public void Foo<T,K>(Expression<Func<T,K>> binding, T item, K value)
What I want to do inside my method is: applying the Func to item, getting the property of type K to which the binding expression points to, and assign "value" to it.
If the binding expression is something like:
c => c.Property
Where "c" is "T", and "Property" is "K", I can use some reflection easily and set the value using FieldInfo. The following code works:
(((binding as LambdaExpression).Body as MemberExpression).Member as FieldInfo).SetValue(item, value);
But the expression could be something like this:
c => c.SubClass.Property
or
c => c.SubClass1.SubClass2.SubClassN.Property
In this case the reflection code doesn't work, as "Property" doesn't belong directly to T, but it's still a valid lambda expression for the signature of the method.
I know that if I compile the Func and run it on my item of type T I get the property, but it's like a "copy" of it, and not a reference of it, so even if I assign the value to it, the property on the original item doesn't get changed.
If anyone has a clean solution to this, or just point me to something that can grant me a better knowledge of Expression Trees, you're very welcome.
struct
somewhere in that 'chain'. For reference types, the assignment will be fine. – leppie Jan 14 '11 at 17:26