title: Create type "MyClass : OtherClass<MyClass> { }" at runtime?
body: <p>Is it possible in C# to create a type at runtime that inherits from a generic class where the template parameter for the base class is the current class being constructed? This will compile fine:</p>
  
  <pre><code>// I have this class:
  public class OtherClass&lt;T&gt;
      where T : OtherClass&lt;T&gt;
  { }
  
  // I want to create this at runtime:
  public class MyClass : OtherClass&lt;MyClass&gt;
  { }
  </code></pre>
  
  <p>but I'm not sure how to create the <code>MyClass</code> using <code>System.Reflection.Emit.ModuleBuilder.TypeBuilder</code>:</p>
  
  <pre><code>AssemblyName asn = new AssemblyName("test.dll");
  AssemblyBuilder asb = AppDomain.CurrentDomain.DefineDynamicAssembly(
      asn, AssemblyBuilderAccess.RunAndSave, @"D:\test_assemblies");
  
  ModuleBuilder = modb = asb.DefineDynamicModule("test", "test.dll");
  
  TypeBuilder tb = modb.DefineType(
      "test",
      TypeAttributes.Public | TypeAttributes.Class,
      typeof(MyClass)); // How to specify inheritance?
  
  // populate properties, fields, methods, etc., emit...
  
  tb.CreateType();
  </code></pre>
  
  <p>Is this possible?</p>
  
  <p>Edit - Based on replies so far, I've tried this:</p>
  
  <pre><code>public class OtherClass&lt;T&gt;
      where T : OtherClass&lt;T&gt;
  { }
  
  public static void CreateSimple()
  {
      AssemblyName asn = new AssemblyName("test");
      AssemblyBuilder asb = AppDomain.CurrentDomain.DefineDynamicAssembly(
          asn, AssemblyBuilderAccess.RunAndSave, @"D:\test_asms");
      ModuleBuilder modb = asb.DefineDynamicModule("test", "test.dll");
  
      try
      {
          TypeBuilder tb = modb.DefineType(
              "MyClass",
              TypeAttributes.Public | TypeAttributes.Class);
  
          Type my = tb.CreateType();
          tb.SetParent(typeof(OtherClass&lt;&gt;).MakeGenericType(my));
  
          my = tb.CreateType();
      }
      catch (Exception e)
      {
          throw;
      }
  }
  </code></pre>
  
  <p>but get this exception:</p>
  
  <pre><code>GenericArguments[0], 'MyClass', on 'MyProject.Factory+OtherClass`1[T]'
  violates the constraint of type 'T'.
  </code></pre>