title: Using reflection in C# to get properties of a nested object
body: <p>Given the following objects:</p>
  
  <pre><code>public class Customer {
      public String Name { get; set; }
      public String Address { get; set; }
  }
  
  public class Invoice {
      public String ID { get; set; }
      public DateTime Date { get; set; }
      public Customer BillTo { get; set; }
  }
  </code></pre>
  
  <p>I'd like to use reflection to go through the <code>Invoice</code> to get the <code>Name</code> property of a <code>Customer</code>.  Here's what I'm after, assuming this code would work:</p>
  
  <pre><code>Invoice inv = GetDesiredInvoice();  // magic method to get an invoice
  PropertyInfo info = inv.GetType().GetProperty("BillTo.Address");
  Object val = info.GetValue(inv, null);
  </code></pre>
  
  <p>Of course, this fails since "BillTo.Address" is not a valid property of the <code>Invoice</code> class.</p>
  
  <p>So, I tried writing a method to split the string into pieces on the period, and walk the objects looking for the final value I was interested in.  It works okay, but I'm not entirely comfortable with it:</p>
  
  <pre><code>public Object GetPropValue(String name, Object obj) {
      foreach (String part in name.Split('.')) {
          if (obj == null) { return null; }
  
          Type type = obj.GetType();
          PropertyInfo info = type.GetProperty(part);
          if (info == null) { return null; }
  
          obj = info.GetValue(obj, null);
      }
      return obj;
  }
  </code></pre>
  
  <p>Any ideas on how to improve this method, or a better way to solve this problem?</p>
  
  <p><strong>EDIT</strong> after posting, I saw a few related posts...  There doesn't seem to be an answer that specifically addresses this question, however.  Also, I'd still like the feedback on my implementation.</p>