Created
July 19, 2013 00:38
-
-
Save AlexArchive/6034249 to your computer and use it in GitHub Desktop.
Demo: Basic Usage of DynamicMethod to Omit Opcodes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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