title: Generic function throws cast exception
body: <p>I have a weird problem. :(</p>
  
  <p>I get an enumerable object from my database and want to convert the objects either to a list of base class objects or to a list of fully blown derived class objects . In some situations I want to cut of attributes I do not need - so standard polymorphism is not the way for me. This function resides in an web service and I have to optimize traffic.</p>
  
  <p>Therefore I wrote a generic function for casting the whole list to the type I want. But in the case of the derived type I get an cast error. But I don't understand the message because the source object has not the type, the message is telling me.</p>
  
  <p>Any ideas what is going wrong? Thx in advance!</p>
  
  <pre class="lang-cs prettyprint-override"><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  
  class DBClass {
      public string id { get; set; }
      public string name { get; set; }
  
      public DBClass() { id = Guid.NewGuid().ToString(); }
  }
  
  class BaseClass {
      public Guid ID { get; set; }
  
      public static explicit operator BaseClass(DBClass x) {
          return new BaseClass() {
              ID = new Guid(x.id)
          };
      }
  }
  
  class DerivedClass : BaseClass {
      public string Name { get; set; }
  
      public static explicit operator DerivedClass(DBClass x) {
          return new DerivedClass() {
              ID = new Guid(x.id),
              Name = x.name
          };
      }
  }
  
  class Program
  {
      static List&lt;BaseClass&gt; convertToList&lt;T&gt;(IEnumerable&lt;DBClass&gt; xx) where T : BaseClass
      {
          // solution from Jeroen Mostert (see comments):
          return xx.Select(obj =&gt; (BaseClass) (T) (dynamic) obj).ToList();
  
          // original code with error
          var l = xx.Select( obj =&gt; (T) obj);
          // T == BaseClass: everything is fine
          // T == DerivedClass: Unable to cast object of type 'BaseClass' to type 'DerivedClass'.
          // but obj is of type DBClass!
  
          return l.ToList() as List&lt;BaseClass&gt;;
      }
  
      static void Main(string[] args)
      {
          List &lt; DBClass &gt;  dbValues = new List&lt;DBClass&gt;();
          dbValues.Add(new DBClass());
          dbValues.Add(new DBClass());
          dbValues.Add(new DBClass());
  
          convertToList&lt;BaseClass&gt;(dbValues);     // ok
          convertToList&lt;DerivedClass&gt;(dbValues);  // KO
      }
  }
  </code></pre>