title: How to create a dynamic type derived from a closed generic type
body: <p>I am trying to dynamically combine any number of types to a new type that inherits all of those types. For now it should only work for interfaces. </p>
  
  <p>I am absolutely aware that there are many pitfalls and a heavy performance impact, but this is only used for my test code - to be more specific, for creating mocks for multiple interfaces.</p>
  
  <p>So, basically I have a class (<code>TypeBuilder</code> - see code below) that is able to create those types. It works out pretty good for "simple" types. But I want to be able to pass it closed generic types as well. When trying to this with my current implementation, a <code>TypeLoadException</code> is thrown when I am trying to create the dynamic type (via <code>TypeBuilder.CreateType</code>).</p>
  
  <p>Do I have to tell the <code>TypeBuilder</code> that the new type is a generic type, although it only derives from closed generic types? If yes, how can I do this?</p>
  
  <p>This is how I use it:</p>
  
  <pre><code>MultiTypeBuilder multiTypeBuilder = 
      new MultiTypeBuilder(Guid.NewGuid().ToString());   
  
  multiTypeBuilder.SetBaseType(typeof(IFoo));
  multiTypeBuilder.SetBaseType(typeof(IBar&lt;IFoo&gt;));
  multiTypeBuilder.SetBaseType(typeof(IBaz));
  
  Type multiType = multiTypeBuilder.CreateType();
  </code></pre>
  
  <p>This is my current implementation (simplified a little bit):</p>
  
  <pre><code>private class MultiTypeBuilder
  {
      private readonly TypeBuilder m_TypeBuilder;
  
      public MultiTypeBuilder(string name)
      {
          ModuleBuilder multiTypeModule = GetMultiTypeModule();
  
          TypeAttributes attributes = TypeAttributes.Interface | TypeAttributes.SpecialName | TypeAttributes.Abstract | TypeAttributes.Public;
  
          m_TypeBuilder = multiTypeModule.DefineType(name, attributes);
      }
  
      public void SetBaseType(Type baseType)
      {
          m_TypeBuilder.AddInterfaceImplementation(baseType);
      }
  
      public Type CreateType()
      {
          return m_TypeBuilder.CreateType();
      }
  
      private static ModuleBuilder GetMultiTypeModule()
      {
          AssemblyName assemblyName = new AssemblyName(c_DynamicAssemblyName);
          AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
          return assemblyBuilder.DefineDynamicModule("MultiTypeAssembly");
      }
  }
  </code></pre>
  
  <p>Thanks for your support!</p>