// File RTCG2D2.cs --- generating and calling a method with argument and result // sestoft@itu.dk * 2003-03-18, 2005-04-12, 2009-02-17 using System; using System.Reflection; using System.Reflection.Emit; // The code below generates a method MyMethod that might have been // declared as follows in C#: // // public static int MyMethod(int x) { // Console.WriteLine("MyMethod() was called"); // return x + 42; // } class RTCG2 { public static void Main(String [] args) { // Build method: public static int MyMethod(int x) { ... } DynamicMethod methodBuilder = new DynamicMethod("MyMethod", // Method name typeof(int), // Return type new Type[] { typeof(int) }, // Arg. types typeof(String).Module); // Module // Obtain an IL generator to build the method body ILGenerator ilg = methodBuilder.GetILGenerator(); ilg.EmitWriteLine("MyMethod() was called"); ilg.Emit(OpCodes.Ldarg_0); ilg.Emit(OpCodes.Ldc_I4, 42); ilg.Emit(OpCodes.Add); ilg.Emit(OpCodes.Ret); int res; // Obtain a delegate referring to the method, and call it: I2I mm = (I2I)methodBuilder.CreateDelegate(typeof(I2I)); res = mm(17); Console.WriteLine(res); } public delegate int I2I(int x); }