Create dynamic method using Reflection in C#

In the below example i had created a dynamic method and call it using IL via Reflection
using System;
using System.Reflection.Emit;
namespace DyanReflectionIL
{
class Program
{
static double Divide(int a,int b)
{
return a/b;
}
static void Main(string[] args)
{
var myMethod = new DynamicMethod("MyDynamicMethod", typeof (double), new[] {typeof (int), typeof (int)},
typeof (Program).Module);
var il = myMethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Div);
il.Emit(OpCodes.Ret);
var result = myMethod.Invoke(null, new object[] {10, 2});
Console.WriteLine(result);
Console.ReadLine();
}
}
}

Enjoy Coding…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s