title: Convert object to generic abstract class
body: <p>I got here a class that looks like this:</p>
  
  <pre><code>public abstract class SIBRegisterHardware2&lt;T&gt; : Register.IRegisterHardware&lt;UInt16, UInt16&gt; where T : IDevice
  {
      protected T open()
      {
         // connect to server and return device T 
      }
  
      // ..
  }
  
  public class Device : SIBRegisterHardware2&lt;IDevice&gt;
  {
      // ..
  }
  </code></pre>
  
  <p>and some derived classes:</p>
  
  <pre><code>internal class DeviceA: SIBRegisterHardware2&lt;IDeviceA&gt;
  {
  }
  
  internal class DeviceB: SIBRegisterHardware2&lt;IDeviceB&gt;
  {
  }
  </code></pre>
  
  <p>Now I am looking for a solution that allows me this:</p>
  
  <pre><code>if(createDevA == true) {
    Device&lt;IDevice&gt; devHandle = new DeviceA();
  } else {
    Device&lt;IDevice&gt; devHandle = new DeviceB():
  }
  </code></pre>
  
  <p>The thing is that code like this produces errors like that:</p>
  
  <pre><code>Cannot implicitly convert type 'DeviceA' to 'SIBRegisterHardware2&lt;IDevice&gt;'
  </code></pre>
  
  <p>Is there a way that would allow me to abstract a template like this?</p>
  
  <hr>
  
  <p>Something I tried out is creating another class that works with reflection:</p>
  
  <pre><code>public class DeviceX : SIBRegisterHardware2&lt;IDevice&gt;
  {
      private Register.IRegisterHardware&lt;UInt16, UInt16&gt; device = null;
      private Type deviceType = null;
  
      public DeviceX (String hwInterfaceClassName)
      {
          if (hwInterfaceClassName.Equals("DeviceA")) {
  
              device = new DeviceA();
              deviceType = device.GetType();
          }
          else if (hwInterfaceClassName.Equals("DeviceB")) {
  
              device = new DeviceB();
              deviceType = device.GetType();
          }
      }
  
      public override String doSomething(int param)
      {
          return (String)deviceType.GetMethod("doSomething").Invoke(device, new object[] { param }); ;
      }
  }
  </code></pre>
  
  <p>but is that a neat design?</p>