title: Casting generic to interface type - Unable to cast object of type 'System.RuntimeType' to type
body: <p>I have some classes like this:</p>
  
  <pre><code>public class Customer
  { }
  
  public interface IRepository 
  { }
  
  public class Repository&lt;T&gt; : IRepository
  { }
  
  public class CustomerRepository&lt;Customer&gt;
  { }
  </code></pre>
  
  <p>Then, as per <a href="https://stackoverflow.com/questions/12462900/identifying-generic-type-of-class-using-reflection">the answer to this question</a> I can use reflection to get a list of types referenced by generics for each of my *Repository:</p>
  
  <p>What I want to end up with is a <code>Dictionary&lt;Type, IRepository&gt;</code></p>
  
  <p>So far, I have this:</p>
  
  <pre><code>Dictionary&lt;Type, IRepository&gt; myRepositories = Assembly.GetAssembly(typeof(Repository&lt;&gt;))
  .GetTypes()
  .Where(typeof(IImporter).IsAssignableFrom)
  .Where(x =&gt; x.BaseType != null &amp;&amp; x.BaseType.GetGenericArguments().FirstOrDefault() != null)
  .Select(
      x =&gt;
      new { Key = x.BaseType != null ? x.BaseType.GetGenericArguments().FirstOrDefault() : null, Type = (IRepository)x })
  .ToDictionary(x =&gt; x.Key, x =&gt; x.Type);
  </code></pre>
  
  <p>However, it doesn't like my cast <code>(IRepository)x</code><br>
  I get the following error:</p>
  
  <blockquote>
    <p>Unable to cast object of type 'System.RuntimeType' to type 'My.Namespace.IRepository'.</p>
  </blockquote>