05 Deriving a Setter from a Lambda Getter

This is a pretty cool hack: Using lambda expression trees, you may actually rewrite the expression tree from a getter to a setter. You can use this hack to capture complete field access from a simple getter.

This is surely possible for properties, too. The following implementation does the trick for fields:

public static class ExpressionExtensions
{
  public static Action<A, B> makeSetter<A, B>(this Expression<Func<A, B>> expression)
  {
    var memberexp = expression.Body as MemberExpression;
    Debug.Assert(memberexp != null && memberexp.Member is FieldInfo);
    var valueParameter = Expression.Parameter(typeof(B), "value");
    var writeCall = Expression.Call(
      typeof(ExpressionExtensions),
      "write",
      new[] { typeof(B) },
      memberexp, 
      valueParameter);
    var exp = Expression.Lambda(
      writeCall,
      expression.Parameters[0],
      valueParameter);
 
    return (Action<A,B>)exp.Compile();
  }
  public static void write<T>(ref T t, T value)
  {
    t = value; 
  }
}

The auxiliary ‘write’ method is required because lambda expressions do not (yet) support assignments.

So what does it for you? Given a lambda that accesses a field of type B from within an instance of type A, for example: ‘(a) => a.MyField’, the method makeSetter builds a compiled lambda in the form ‘(a, b) => a.MyField = b’.