Last active
August 29, 2015 14:05
-
-
Save nguerrera/7f9d578e8e3d11c44f7b to your computer and use it in GitHub Desktop.
Creating a delegate bound to a static method with first argument in verifiable IL
This file contains hidden or 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
// And this program can be writen in C# after all if you use an extension method! | |
// (And the codegen is exactly as the optimal hand-written IL below.) | |
// | |
// Thanks to Vladimir Sadov on the compiler team for teaching me about it! | |
static class Program | |
{ | |
static void Main() | |
{ | |
var f = new Func<string>("World".StaticMethod); | |
Console.WriteLine(f()); | |
} | |
static string StaticMethod(this string x) | |
{ | |
return x + " World"; | |
} | |
} |
This file contains hidden or 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
.assembly extern mscorlib | |
{ | |
.publickeytoken = (B7 7A 5C 56 19 34 E0 89) | |
.ver 4:0:0:0 | |
} | |
.assembly DelegateToStaticWithFirstArg {} | |
.module DelegateToStaticWithFirstArg.exe | |
.class Program extends [mscorlib]System.Object | |
{ | |
.method private static void Main() | |
{ | |
.entrypoint | |
// create delegate for StaticMethod invoked with "World" as first argument | |
ldstr "World" | |
ldftn string Program::StaticMethod(string) | |
newobj instance void class [mscorlib]System.Func`1<string>::.ctor(object, native int) | |
// invoke delegate | |
callvirt instance !0 class [mscorlib]System.Func`1<string>::Invoke() | |
// write result of invocation to console | |
call void [mscorlib]System.Console::WriteLine(string) | |
ret | |
} | |
.method private static string StaticMethod(string firstArg) | |
{ | |
// return "Hello " + firstArg | |
ldstr "Hello " | |
ldarg.0 | |
call string [mscorlib]System.String::Concat(string, string) | |
ret | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment