what is the Linq expression tree for setting a property of an object?

.net-4.0 c# expression-trees linq

Question

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 can I rewrite the definition of fnSet using an expression trees, e.g.:

public void SetThree( Foo x )
{
   var assign = *** WHAT GOES HERE? ***
   Action<foo,int> fnSet = assign.Compile();

   fnSet(x, 3);
}

Accepted Answer

Here's 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 out "3".



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