// File RTCG2.cs --- calling a static method with int argument and result // sestoft@itu.dk * 2002 using System; using System.Reflection; using System.Reflection.Emit; class RTCG2 { public static void Main(String [] args) { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "myassembly"; // Build: run-only assembly AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); // Build: module mymodule ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("mymodule"); // Build: public class MyClass { ... } TypeBuilder typeBuilder = moduleBuilder.DefineType("MyClass", TypeAttributes.Class | TypeAttributes.Public, typeof(Object)); // Build: public static int MyMethod(int x) { return x + 2; } MethodBuilder methodBuilder = typeBuilder.DefineMethod("MyMethod", MethodAttributes.Static | MethodAttributes.Public, typeof(int), new Type[] { typeof(int) }); // Obtain an IL generator to build the method body ILGenerator ilg = methodBuilder.GetILGenerator(); ilg.EmitWriteLine("MyClass.MyMethod() was called"); ilg.Emit(OpCodes.Ldarg_0); ilg.Emit(OpCodes.Ldc_I4_2); ilg.Emit(OpCodes.Add); ilg.Emit(OpCodes.Ret); Type ty = typeBuilder.CreateType(); // Now call MyClass.MyMethod(5) using reflection: int res = (int)ty.GetMethod("MyMethod").Invoke(null, new object[] { 5 }); Console.WriteLine(res); // Or create a delegate and call that instead: IntInt mm = (IntInt)Delegate.CreateDelegate(typeof(IntInt), ty.GetMethod("MyMethod")); Console.WriteLine(mm(15)); } public delegate int IntInt(int x); }