AssemblyName assemblyName = new AssemblyName("MyAssembly"); AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule"); TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public); ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[0]); ILGenerator ilGenerator = constructorBuilder.GetILGenerator(); ilGenerator.Emit(OpCodes.Ret); Type myType = typeBuilder.CreateType();
TypeBuilder typeBuilder = // get a TypeBuilder instance MethodBuilder methodBuilder = typeBuilder.DefineMethod("MyMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[0]); ILGenerator ilGenerator = methodBuilder.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldc_I4, 42); ilGenerator.Emit(OpCodes.Ret); Type myType = typeBuilder.CreateType();This code creates a new method called "MyMethod" in a TypeBuilder instance, generates IL code that pushes 42 onto the stack and returns it, and then creates the type. In conclusion, the System.Reflection.Emit ModuleBuilder is a powerful tool that allows developers to create custom types and methods at runtime. It's part of the .NET Framework Class Library and is available in the System.Reflection.Emit namespace of the mscorlib.dll assembly.