title: C# casting the result of GetValue from PropertyInfo to a generic list
body: <p>Im trying to build an application where the properties of the classes are set based on the values in som XML files.<br>
  Some of the classes has properties consisting of a list of of it's children. Due to the way i made this program, the properties has to be set via propertyinfo classes. My problem is that i have trouble with fetcing the list of children (ICollection in <em>Derived2</em>). <br>It must be cast to a generic list (<em>ICollection</em> OR <em>HashSet</em>), so i dont have to copy paste the same setChild method in each derived class.
  I've tried casting the <em>GetValue</em> return value to either <em>ICollection</em>, <em>HashSet</em> or <em>IENumerable</em>, none worked. 
  <br>Maybe the solution could be to use another method of the <em>PropertyInfo</em> class?
  <br>A somewhat simplified code example code:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public interface Superclass
  {}
  
  public class Derived1 : Superclass {}
  
  public class Derived2 : Superclass
  {
      public Derived2()
      {
          PatientForloeb = new HashSet&lt;Derived1&gt;();
      }
      public virtual ICollection&lt;Derived1&gt;Derived1{ get; set; }
  }
  
  class Program
  {
      static void Main(string[] args)
      {
          List&lt;Derived1&gt; children = new List&lt;Derived1&gt;();
          children.Add(new Derived1());
  
          var parent = new Derived2();
          setChild(parent, children);
      }
  
      private static void setChild(Superclass parent, List&lt;Derived1&gt; children)
      {
          foreach (var child in children)
          {
              var p = (parent.GetType().GetProperty(child.GetType().Name)); // This is ugly, should be based on type not name, but it works for my app.
              var pi = p.GetValue(parent) as HashSet&lt;Superclass&gt;; ///////////&lt;-------This gives null. This is the problem.
              pi.add(child);
          }
      }
  }
  </code></pre>