title: Casting an object to a IList with an abstract type parameter
body: <p>In my code, I have an object:</p>
  
  <pre><code>object obj = ...
  </code></pre>
  
  <p>Which I know is of type MyListType, where MyListType is a subclass of IList and T is a subclass of MyAbstractClass. The type parameter of MyListType is constrained so that it is always a subclass of MyAbstractClass.</p>
  
  <p>However, trying to cast obj</p>
  
  <pre><code>MyListType&lt;MyAbstractClass&gt; myList = (MyListType&lt;MyAbstractClass&gt;)obj;
  </code></pre>
  
  <p>gives a runtime error.</p>
  
  <p>I tried to define an explicit operator</p>
  
  <pre><code>public static explicit operator MyListType&lt;MyAbstractClass&gt;(MyListType&lt;T&gt; list)
  {
      MyListType&lt;MyAbstractClass&gt; newList = new MyListType&lt;MyAbstractClass&gt;();
      foreach(T t in list)
          newList.Add((MyAbstractClass) t);
      return newList;
  }
  </code></pre>
  
  <p>However, this operator doesn't get used by the cast since obj is an object, not a MyListType. Is there a workaround to successfully perform this cast?</p>
  
  <p>I've looked at <a href="https://stackoverflow.com/questions/2837063/cast-object-to-generic-list">this question</a>, but their the list was of an unknown type.</p>