// Define a dynamic assembly. AssemblyBuilder dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("MyAssembly"), AssemblyBuilderAccess.Run); // Define a dynamic module in the assembly. ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("MyModule"); // Define a dynamic class in the module. TypeBuilder dynamicClass = dynamicModule.DefineType("MyClass", TypeAttributes.Public); // Define a method in the class. MethodBuilder dynamicMethod = dynamicClass.DefineMethod("MyMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { }); // Define IL generator for the method. ILGenerator ilGenerator = dynamicMethod.GetILGenerator(); // Emit a comment in the generated code. ilGenerator.EmitComment("This is a comment."); // Finish the method. ilGenerator.Emit(OpCodes.Ret); // Create the class type. Type myType = dynamicClass.CreateType();
// Define a dynamic assembly. AssemblyBuilder dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("MyAssembly"), AssemblyBuilderAccess.Run); // Define a dynamic module in the assembly. ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("MyModule"); // Define a dynamic class in the module. TypeBuilder dynamicClass = dynamicModule.DefineType("MyClass", TypeAttributes.Public); // Define a method in the class. MethodBuilder dynamicMethod = dynamicClass.DefineMethod("MyMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { }); // Define IL generator for the method. ILGenerator ilGenerator = dynamicMethod.GetILGenerator(); // Emit a comment in the generated code. ilGenerator.EmitComment("This is another comment."); // Define a local variable in the method. LocalBuilder myLocal = ilGenerator.DeclareLocal(typeof(int)); // Load a constant value of 10 onto the stack. ilGenerator.Emit(OpCodes.Ldc_I4, 10); // Store the value in the local variable. ilGenerator.Emit(OpCodes.Stloc, myLocal); // Finish the method. ilGenerator.Emit(OpCodes.Ret); // Create the class type. Type myType = dynamicClass.CreateType();In this example, a dynamic assembly is defined and a method is generated with two comments using the EmitComment method. Additionally, a local variable is defined, a constant value is loaded onto the stack, and the value is stored in the local variable. Package Library: System.Reflection.Emit namespace.