Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
like image 370
Eric Avatar asked Oct 07 '11 22:10

Eric


1 Answers

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".

like image 180
Kirk Woll Avatar answered Nov 14 '22 22:11

Kirk Woll