title: How to Get and Set a Property using Expression Trees in the Best Way?
body: <p>Instead of using Reflection, how can I set and get object properties using Expression Trees?</p>
  
  <p>I have written the below class which works fine:</p>
  
  <pre><code>public class PropertyAccessor&lt;TEntity&gt;
      {
          private readonly PropertyInfo _memberInfo;
          private readonly TEntity _nom;
  
          public PropertyAccessor(Expression&lt;Func&lt;TEntity, object&gt;&gt; fieldSelector, TEntity nom)
          {
              if (fieldSelector.Body is MemberExpression)
                  _memberInfo = (PropertyInfo)((MemberExpression)fieldSelector.Body).Member;
  
              else if (fieldSelector.Body is UnaryExpression)
                  _memberInfo = (PropertyInfo)((MemberExpression)((UnaryExpression)fieldSelector.Body).Operand).Member;
              else
                  throw new NotImplementedException("Field selector not supported");
  
              _nom = nom;
          }
  
          public object Value
          {
              get { return _memberInfo.GetValue(_nom, null); }
              set { _memberInfo.SetValue(_nom, value, null); }
          }
      }
  </code></pre>
  
  <p>and I use it like this:</p>
  
  <pre><code>Product product = ProductFactory.Build();
  var propertyAccessor = new PropertyAccessor&lt;Product&gt;(p =&gt; p.Name, product);
  var name = propertyAccessor.Value;
  </code></pre>
  
  <p>Is there any way to improve its performance further? Is the implementation the best way to do it?</p>
  
  <p>Shouldn't I call the Compile() method on the expression before or after the constructor call?</p>
  
  <p>What happens when a lambda expression is passed to an Expression of that lambda expression?</p>
  
  <p>Is converting the MemberExpression to a PropertyInfo the best option? any performance penalties?</p>