The System.Reflection.Emit namespace provides us the tools required to generate .NET code on the fly. Especially the DynamicMethod class makes the job of creating small code snippet easier. In this post I’ll show a simple example of dynamically creating a method which takes a string as its argument and returns a string “hi “prepended to it. First, we will create the DynamicMethod object specifying the argument list and the return

type of the dynamic method. Next we will emit the MSIL required to do the task, yes, we can only create dynamic methods using MSIL. Then we will create a delegate from our dynamic method. Then we can call the delegate like we would do with any delegate.Okay, let us declare the delegate first//Delegate matching the method to be generateddelegate string SayHi(string name);Now, let us look at the actual code://create the DynamicMethod objectDynamicMethod method=new DynamicMethod("method",//Method nametypeof(string),//The return typenew Type[]{typeof(string)},//array of types specifying the type of arguments and their ordertypeof(Program).Module //The module to which the method will be connected);//Create the IL generaterILGenerator il=method.GetILGenerator();//Load the const string "hi " on to the evaluation stackil.Emit(OpCodes.Ldstr,"Hi ");//Load the argument, the nameil.Emit (OpCodes.Ldarg_0 );//call the string.Concat() with 2 string parametersil.EmitCall(OpCodes.Call,typeof(string).GetMethod("Concat",new Type[]{typeof(string),typeof(string)}) ,//Find and pass the overload of Concat which accepts 2 stringsnull );//return, effectivly returning the result of string.Concat()il.Emit(OpCodes.Ret);// Complete the IL generation and create a delegateSayHi hi=(SayHi)method.CreateDelegate(typeof(SayHi));//execute our generated method with "nirandas" as the parameterMessageBox.Show(hi("Nirandas"));For more information about dynamic method creation, visit this MSDN page.Happy coding!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList