title: C# Reflection get Field or Property by Name
body: <p>Is there a way to supply a name to a function that then returns the value of either the field or property on a given object with that name? I tried to work around it with the null-coalesce  operator, but apparently that doesn't like different types (which is also a bit weird to me because null is null). I could separate it it out into if nulls, but there has to be a better way to do this. Here is my function, and the two lines with <code>Comparison</code> objects don't compile, but I will leave them in there to show what I am trying to do.</p>
  <pre><code>private void SortByMemberName&lt;T&gt;(List&lt;T&gt; list, string memberName, bool ascending)
  {
     Type type = typeof (T);
     MemberInfo info = type.GetField(memberName) ?? type.GetProperty(memberName);
  
     if (info == null)
     {
          throw new Exception(&quot;Member name supplied is neither a field nor property of type &quot; + type.FullName);
     }
  
     Comparison&lt;T&gt; asc = (t1, t2) =&gt; ((IComparable) info.GetValue(t1)).CompareTo(info.GetValue(t2));
     Comparison&lt;T&gt; desc = (t1, t2) =&gt; ((IComparable) info.GetValue(t2)).CompareTo(info.GetValue(t1));
  
      list.Sort(ascending ? asc : desc);
  }
  </code></pre>
  <p>I have heard of something called dynamic LINQ that could be used, but for the sake of learning, I am doing it my way.</p>