title: C# Type-casting oddity - interface as the generic type
body: <p>I've just run into what I think is an oddity in type-casting. I have code similar to the following:</p>
  
  <pre><code>interface IMyClass { }
  
  class MyClass: IMyClass { }
  
  class Main
  {
    void DoSomething(ICollection&lt;IMyClass&gt; theParameter) { }
  
    HashSet&lt;MyClass&gt; FillMyClassSet()
    {
      //Do stuff
    }
  
    void Main()
    {
      HashSet&lt;MyClass&gt; classSet = FillMyClassSet();
      DoSomething(classSet);
    }
  }
  </code></pre>
  
  <p>When it gets to DoSomething(classSet), the compiler complains that it can't cast HashSet&lt;MyClass&gt; to ICollection&lt;IMyClass&gt;. Why is that? HashSet implements ICollection, MyClass implements IMyClass, so why isn't the cast valid?</p>
  
  <p>Incidentally this isn't hard to work around, thought it's slightly awkward.</p>
  
  <pre><code>void Main()
  {
    HashSet&lt;MyClass&gt; classSet = FillMyClassSet();
    HashSet&lt;IMyClass&gt; interfaceSet = new HashSet&lt;IMyClass&gt;();
    foreach(IMyClass item in classSet)
    {
      interfaceSet.Add(item);
    }
    DoSomething(interfaceSet);
  }
  </code></pre>
  
  <p>To me, the fact that this works makes the inability to cast even more mysterious.</p>