Tuesday, October 13, 2009

DynamicMethod in C#

DynamicMethod, One of the interesting and not so useful feature in .NET 2.0. It is a part of System.Reflection.Emit namespace. It allows to create and execute the methods at runtime without creating any dynamic assembly or dynamic type. It has one interesting thing; when a DynamicMethod is bound to a type, it will have access to all private and public members of that type.

Below is one simple sample for using the DynamicMethod

static void Main(string[] args)

{
Type[] helloArgs = { typeof(string), typeof(int) };
DynamicMethod hello = new DynamicMethod("Hello",
typeof(int),
helloArgs,
typeof(string).Module);


Type[] writeStringArgs = { typeof(string) };
MethodInfo writeString = typeof(Console).GetMethod("WriteLine",writeStringArgs);
ILGenerator il = hello.GetILGenerator(256);
// Load the first argument, which is a string, onto the stack.
il.Emit(OpCodes.Ldarg_0);
// Call the overload of Console.WriteLine that prints a string.
il.EmitCall(OpCodes.Call, writeString, null);
// The Hello method returns the value of the second argument;
// to do this, load the onto the stack and return.
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ret);
object[] invokeArgs = { "\r\nHello, World!", 42 };
object objRet = hello.Invoke(null, BindingFlags.ExactBinding, null, invokeArgs, new CultureInfo("en-us"));
Console.WriteLine("hello.Invoke returned: " + objRet);
}

No comments:

Post a Comment