what's the purpose of calling TypeBuilder.CreateType()

80 Views Asked by At

I have difficulty in understanding in creating a dynamic assembly, below is some code:

public static void CreateMyAsm(AppDomain curAppDomain)
{
   AssemblyName assemblyName = new AssemblyName();
   assemblyName.Name = "MyAssembly";
   assemblyName.Version = new Version("1.0.0.0");
   AssemblyBuilder assembly = curAppDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
   ModuleBuilder module =
   assembly.DefineDynamicModule("zMyAssembly", "zMyAssembly.dll");
   TypeBuilder helloWorldClass = module.DefineType("zMyAssembly.HelloWorld", TypeAttributes.Public);

  /*
   ...configure ConstructorBuilder, FieldBuilder, MethodBuilder  etc with ILGenerator.Emit() here

  ConstructorBuilder constructor = helloWorldClass.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, constructorArgs);
  ILGenerator constructorIL = constructor.GetILGenerator();
  ...
  FieldBuilder msgField = helloWorldClass.DefineField("theMessage", Type.GetType("System.String"),FieldAttributes.Private);
  constructorIL.Emit(OpCodes.Stfld, msgField);
  */  
   helloWorldClass.CreateType();
   assembly.Save("MyAssembly.dll");
}

so my question is, why do we need to call helloWorldClass.CreateType();, which creates a type?

Because we normailly get a Type in the main method as:

static void Main(string[] args)
{
   ...
   Type t = Type.GetType("MyAssembly.HelloWorld, MyAssembly");
   ...
}

so we can get the type dynamically?

EDIT: someone says Type.GetType returns existing metadata. AssemblyBuilder.CreateType introduces new metadata.

so all the TypeBuilder.DefineMethod, TypeBuilder.DefineField, TypeBuilder.DefineConstructor etc don't 'introduce' metadata? shouldn't it be more sensible that calling TypeBuilder.DefineXXX automatically 'write' or 'introduce' metadata on the go, so AssemblyBuilder.CreateType() is not needed anymore?

0

There are 0 best solutions below