title: How to make a generic class with inheritance?
body: <p>How can I make the following code work?  I don't think I quite understand C# generics.  Perhaps, someone can point me in the right direction.</p>
  
  <pre><code>    public abstract class A
      {
      }
  
      public class B : A
      {
      }
  
      public class C : A
      {
      }
  
      public static List&lt;C&gt; GetCList()
      {
          return new List&lt;C&gt;();
      }
  
      static void Main(string[] args)
      {
          List&lt;A&gt; listA = new List&lt;A&gt;();
  
          listA.Add(new B());
          listA.Add(new C());
  
          // Compiler cannot implicitly convert
          List&lt;A&gt; listB = new List&lt;B&gt;();
  
          // Compiler cannot implicitly convert
          List&lt;A&gt; listC = GetCList();
  
          // However, copying each element is fine
          // It has something to do with generics (I think)
          List&lt;B&gt; listD = new List&lt;B&gt;();
          foreach (B b in listD)
          {
              listB.Add(b);
          }
      }
  </code></pre>
  
  <p>It's probably a simple answer.  </p>
  
  <p>Update:
  First, this is not possible in C# 3.0, but will be possible in C# 4.0.</p>
  
  <p>To get it running in C# 3.0, which is just a workaround until 4.0, use the following:</p>
  
  <pre><code>        // Compiler is happy
          List&lt;A&gt; listB = new List&lt;B&gt;().OfType&lt;A&gt;().ToList();
  
          // Compiler is happy
          List&lt;A&gt; listC = GetCList().OfType&lt;A&gt;().ToList();
  </code></pre>