Home   Cover Cover Cover Cover
 

Dynamic code creation

Chap4_Ex22.cs
using System;
using System.Reflection;
using System.Reflection.Emit;

public class DynTypeCreation {
  
  public static void Main(string[] args) {
    //----- create an assembly
    AssemblyName assemblyName = new AssemblyName();
    assemblyName.Name = "TestReflection";
    AssemblyBuilder newAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly
      (assemblyName, AssemblyBuilderAccess.Run);
    //----- create a module within the new assembly
    ModuleBuilder newModule = newAssembly.DefineDynamicModule("TestReflectionModule");
    //----- create a type within the new module
    TypeBuilder newType = newModule.DefineType("TestReflection", TypeAttributes.Public);
    //----- create a method without parameters
    MethodBuilder woMethod = newType.DefineMethod("WithoutParameters", MethodAttributes.Public | MethodAttributes.Virtual, null, null);
    //----- insert CIL instructions into the new method
    ILGenerator ilGen = woMethod.GetILGenerator();
    ilGen.Emit(OpCodes.Ret);
    
    //----- create a method with parameters
    Type[] paramTypes = { typeof(string) };
    Type retType = typeof(bool);
    MethodBuilder wMethod = newType.DefineMethod("WithParameters", MethodAttributes.Public | MethodAttributes.Virtual, retType, paramTypes);
    //----- insert CIL instructions into the new method
    ilGen = wMethod.GetILGenerator();
    ilGen.Emit(OpCodes.Ldc_I4_1);
    ilGen.Emit(OpCodes.Stloc_0);
    ilGen.Emit(OpCodes.Br_S);
    ilGen.Emit(OpCodes.Ldloc_0);
    ilGen.Emit(OpCodes.Ret);

    //----- finish new type
    newType.CreateType();    
  }
}