Built-in MSIL / CIL

I created the following simple method:

public static void Main () {
    Console.WriteLine("Hello world!");
    Console.ReadKey(true);
}

Then I used ILSpy to get the MSIL code:

.method public hidebysig static void Main() cil managed {
    .entrypoint
    .maxstack  8
    nop
    ldstr "Hello world!"
    call void [mscorlib]System.Console::WriteLine(string)
    nop
    ldc.i4.1
    call valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey(bool)
    pop
    ret
}

Finally, I tried to write the MSIL code in my C # code using the trick #if ILI found here .

public static void Main () {
    #if IL
        nop
        ldstr "Hello world!"
        call void [mscorlib]System.Console::WriteLine(string)
        nop
        ldc.i4.1
        call valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey(bool)
        pop
        ret
    #else
        Console.WriteLine("Hello world!");
        Console.ReadKey(true);
    #endif
}

I tried this trick with nopand without nop, but with #elseand without, but Visual Studio never compiled MSIL code. Where is my mistake or is there another way (if there is a way) to write MSIL code in C # code?

+4
source share

All Articles