using System; using System.Reflection; using System.Reflection.Emit; class Program { static void Main() { AssemblyName asmName = new AssemblyName("DynamicAssembly"); AssemblyBuilder asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = modBuilder.DefineType("MyClass", TypeAttributes.Public); MethodBuilder methodBuilder = typeBuilder.DefineMethod("Add", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) }); ILGenerator ilGen = methodBuilder.GetILGenerator(); ilGen.Emit(OpCodes.Ldarg_0); ilGen.Emit(OpCodes.Ldarg_1); ilGen.Emit(OpCodes.Add); ilGen.Emit(OpCodes.Ret); typeBuilder.CreateType(); asmBuilder.Save("DynamicAssembly.dll"); } }
using System; using System.Reflection; using System.Reflection.Emit; class Program { static void Main() { AssemblyName asmName = new AssemblyName("DynamicAssembly"); AssemblyBuilder asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = modBuilder.DefineType("MyClass", TypeAttributes.Public); MethodBuilder methodBuilder = typeBuilder.DefineMethod("PrintMessage", MethodAttributes.Public | MethodAttributes.Static, null, null); ILGenerator ilGen = methodBuilder.GetILGenerator(); Label endLabel = ilGen.DefineLabel(); ilGen.Emit(OpCodes.Ldstr, "Hello, world!"); ilGen.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) })); ilGen.Emit(OpCodes.Br_S, endLabel); ilGen.MarkLabel(endLabel); ilGen.Emit(OpCodes.Ret); typeBuilder.CreateType(); asmBuilder.Save("DynamicAssembly.dll"); } }In this example, we define a new method called "PrintMessage" that prints "Hello, world!" to the console. We generate the MSIL code to load the string onto the stack, call the Console.WriteLine() method, and jump to the end of the method using a label and the Br_S opcode. We then mark the label using the MarkLabel() method and return from the method using the Ret opcode. We again save the assembly as "DynamicAssembly.dll". Library: System.Reflection.Emit