title: How to assign a value via Expression?
body: <p>This would be very simple if I were able to assign via a Lambda expression (below)</p>
  
  <pre><code>//An expression tree cannot contain an assignment operator
  Expression&lt;Func&lt;ComplexObj, object&gt;&gt; expression = obj =&gt; obj.Contacts[0].FirstName = "Tim";
  </code></pre>
  
  <p>This code above is invalid due to the assignment operator. I need to pass a lambda expression in order to identify the property in the complex object that needs to be set. In some cases the complex object has List and therefor duplicate object types and names which is why I need the lambda to explicitly reference the field in the object to be updated.</p>
  
  <p>I am able to retrieve the value using the following, no problem. But I am not sure how to use this same logic to set the value, I came across Expression.Assign and believe this may be the solution.</p>
  
  <pre><code>Expression&lt;Func&lt;ComplexObj, object&gt;&gt; expression = obj =&gt; obj.Contacts[0].FirstName;
  var result = FindByProperty(expression);
  
  public static string FindByProperty(Expression&lt;Func&lt;Contract, object&gt;&gt; propertyRefExpr)
  {
      ComplexObj obj = new ComplexObj();
      Contact myContact = new Contact();
      myContact.FirstName = "Allen";
      obj.Contacts = new List&lt;Contact&gt;{myContact};
      return propertyRefExpr.Compile().Invoke(obj);
  }
  </code></pre>
  
  <p><strong>Update:</strong></p>
  
  <p>"passing a property assignment to a method as an expression tree..."</p>
  
  <p>Using the SetValue method with ParentTypeA, Value will not work. (below code)</p>
  
  <pre><code>Expression&lt;Func&lt;ComplexObj, object&gt;&gt; expression = obj =&gt; obj.Contacts[0].FirstName;
  obj.AssignNewValue(expression, firstName);
  
  public static void AssignNewValue(this ComplexObj obj, Expression&lt;Func&lt;ComplexObj, object&gt;&gt; expression, object value)
  {
      var propertyInfo = (PropertyInfo)((MemberExpression)expression.Body).Member;
      propertyInfo.SetValue(obj, value, null);
  }
  </code></pre>