title: C# Use Generics and Expression Trees to get object field values
body: <p>I have two classes with similar fields:</p>
  
  <pre><code>Class Foo {
      string name;
      int val;
  };
  
  Class Bar {
      string name;
      int val;
  };
  </code></pre>
  
  <p>Is there a way to use Generics to retrieve the field names and values of objects of these classes? Something along the lines of:</p>
  
  <pre><code>string GetName&lt;T&gt; (T obj)
  {
      //returns T.name
  }
  </code></pre>
  
  <p>I want to make sure there are compile time checks for this, in case the class fields were to change.</p>
  
  <p>Update:</p>
  
  <p>I do not control the definitions of classes Foo and Bar. They will be exposed to me in a library and can change.</p>
  
  <p>I can use something like the following:</p>
  
  <pre><code>Type myType = myObject.GetType();
  var value = myType.GetProperty("name").GetValue(myObject, null);
  </code></pre>
  
  <p>But I don't think this would check at compile time.</p>