title: Get value and name of property of an object
body: <p>I'm trying to build some objects based on properties coming from another object. The class of the objects I need to build is</p>
  
  <pre><code>public class Data
  {
      public string Attribute { get; set; }
      public string Value{ get; set; }
  }
  </code></pre>
  
  <p>And the attribute will be the name of the property (and the value its value)</p>
  
  <p>So I was trying to use Expressions trees to make a method that I can use for avoiding hard coding that attribute</p>
  
  <p>Up to the moment I came to these couple of methods, based on a couple of posts I was reading on the net</p>
  
  <pre><code>public static string GetName&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; e)
  {
      var member = (MemberExpression)e.Body;
      return member.Member.Name;
  }
  
  public static Data BuildData&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; e, appDetailCategory category)
  {
      var member = (MemberExpression)e.Body;
      Expression strExpr = member.Expression;
  
      var name = member.Member.Name;
      var value = Expression.Lambda&lt;Func&lt;string&gt;&gt;(strExpr).Compile()();
  
      return new Data
      {
          Attribute = name,
          Value = value
      };
  }
  </code></pre>
  
  <p>But the line I'm trying to set the value raises an exception:</p>
  
  <pre><code>Expression of type 'AutomapperTest.Program+DecisionRequest' cannot be used for return type 'System.String'
  </code></pre>
  
  <p>I'm pretty sure this message it's supposed to make the error obvious but it's not for me</p>
  
  <p>UPDATE: </p>
  
  <p>I'm calling it this way</p>
  
  <pre><code>private static Data[] GetApplicatonDetailsFromRequest(DecisionRequest request)
  {
          BuildData(() =&gt; request.PubID)
  
          //...
  
  }
  </code></pre>