title: C# typesafe cloning with generics
body: <p>I'm trying to create a generic container object (done; no problem) which can be deep cloned. That means it has to deep clone its contained objects, and it's this that is causing me problems. Here's some code:</p>
  <pre><code>    public abstract class VehiclePart {
          public abstract T cloneTypesafe&lt;T&gt;()
                          where T : VehiclePart, new() // L1
      }
  
  
      public class Gearstick : VehiclePart { // L2
  
          public Gearstick() { }
  
          public override T cloneTypesafe&lt;T&gt;() {
              var res2 = new Gearstick();
              return res2; // L3
              return (T)res2; // L4
          }
      }
  </code></pre>
  <p>It rejects this (comment L3) saying “Cannot implicitly convert type 'LDB.Program.Gearstick' to 'T'”, but that makes no sense because T is explicitly derived from VehiclePart (Line L1), and Gearstick is explicitly derived from VehiclePart (line L2), so the conversion should be entirely legal.</p>
  <p>Even if I had an explicit cast (line L4) it's not happy (&quot;Cannot convert type 'LDB.Program.Gearstick' to 'T'&quot;), so what's the problem and how do I fix this?  (I don’t want to use reflection, which seems to be a common suggestion in answers to similar questions. I have read several comments saying not to use ICloneable).</p>