What is a Linq expression tree for setting an object property?

Suppose I have:

class Foo { public int Bar { get; set; } } public void SetThree( Foo x ) { Action<Foo, int> fnSet = (xx, val) => { xx.Bar = val; }; fnSet(x, 3); } 

How to rewrite the definition of fnSet using expression trees, for example:

 public void SetThree( Foo x ) { var assign = *** WHAT GOES HERE? *** Action<foo,int> fnSet = assign.Compile(); fnSet(x, 3); } 
+4
source share
1 answer

Here is an example.

 void Main() { var fooParameter = Expression.Parameter(typeof(Foo)); var valueParameter = Expression.Parameter(typeof(int)); var propertyInfo = typeof(Foo).GetProperty("Bar"); var assignment = Expression.Assign(Expression.MakeMemberAccess(fooParameter, propertyInfo), valueParameter); var assign = Expression.Lambda<Action<Foo, int>>(assignment, fooParameter, valueParameter); Action<Foo,int> fnSet = assign.Compile(); var foo = new Foo(); fnSet(foo, 3); foo.Bar.Dump(); } class Foo { public int Bar { get; set; } } 

Prints "3".

+7
source

All Articles