Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Created July 19, 2013 00:38
Show Gist options
  • Save AlexArchive/6034249 to your computer and use it in GitHub Desktop.
Save AlexArchive/6034249 to your computer and use it in GitHub Desktop.
Demo: Basic Usage of DynamicMethod to Omit Opcodes
public sealed class Program
{
static void Main(string[] args)
{
var result = Math.AddNumbers(10, 20);
Console.WriteLine(result);
Console.ReadKey();
}
}
public static class Math
{
public static int AddNumbers(int numberOne, int numberTwo)
{
var dynamicMethod =
new DynamicMethod("AddNumbers", typeof (int), new [] {typeof (int), typeof (int)});
var generator = dynamicMethod.GetILGenerator();
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldarg_1);
generator.Emit(OpCodes.Add);
generator.Emit(OpCodes.Ret);
var dynamicMethodDelegate =
dynamicMethod.CreateDelegate(typeof (Func<int, int, int>));
var addNumbersDelegate = (Func<int, int, int>) dynamicMethodDelegate;
return addNumbersDelegate(numberOne, numberTwo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment