title: Generics and casting - cannot cast inherited class to base class
body: <p>I know this is old, yet I am still not very good with understanding those problems. Can anyone tell me why the following does not work (throws a <code>runtime</code> exception about casting)?</p>
  
  <pre><code>public abstract class EntityBase { }
  public class MyEntity : EntityBase { }
  
  public abstract class RepositoryBase&lt;T&gt; where T : EntityBase { }
  public class MyEntityRepository : RepositoryBase&lt;MyEntity&gt; { }
  </code></pre>
  
  <p>And now the casting line:</p>
  
  <pre><code>MyEntityRepository myEntityRepo = GetMyEntityRepo(); // whatever
  RepositoryBase&lt;EntityBase&gt; baseRepo = (RepositoryBase&lt;EntityBase&gt;)myEntityRepo;
  </code></pre>
  
  <p>So, can anyone explain how is this invalid? And, I you are not in the mood to explain - is there a line of code I can use to actually do this cast?</p>