Search code examples
c#cil

how do i compile c# code to IL code instructions


Im making a thing that recompiles executeables with modifyed IL code and need to get the OPcode instructions (no classes, methods etc just the instructions) so that i can just add/replace it in the method and then recompile it.

is there someway i can compile this c# code:

int a = 5;
int b = 24;
Console.WriteLine("{0} * {1} = {2}",a,b,a*b);

to the il code:

.entrypoint
// Code size       38 (0x26)
.maxstack  5
.locals init ([0] int32 a,
         [1] int32 b)
IL_0000:  nop
IL_0001:  ldc.i4.5
IL_0002:  stloc.0
IL_0003:  ldc.i4.s   24
IL_0005:  stloc.1
IL_0006:  ldstr      "{0} * {1} = {2}"
IL_000b:  ldloc.0
IL_000c:  box        [mscorlib]System.Int32
IL_0011:  ldloc.1
IL_0012:  box        [mscorlib]System.Int32
IL_0017:  ldloc.0
IL_0018:  ldloc.1
IL_0019:  mul
IL_001a:  box        [mscorlib]System.Int32
IL_001f:  call       void [mscorlib]System.Console::WriteLine(string,
                                                              object,
                                                              object,
                                                              object)
IL_0024:  nop
IL_0025:  ret

so that i can replace it and reassemble it with ilassem?


Solution

  • If you're looking for a tool that can show you the IL, you can use LINQPad:

    1. Select "C# Statements"
    2. Type your code
    3. Optional: by pressing the button in the lower right corner of the window, choose whether you want to see optimized IL or not
    4. Press F5 or the green Execute button
    5. Select the IL tab

    The result for your code is:

    IL_0000:  nop         
    IL_0001:  ldc.i4.5    
    IL_0002:  stloc.0     // a
    IL_0003:  ldc.i4.s    18 
    IL_0005:  stloc.1     // b
    IL_0006:  ldstr       "{0} * {1} = {2}"
    IL_000B:  ldloc.0     // a
    IL_000C:  box         System.Int32
    IL_0011:  ldloc.1     // b
    IL_0012:  box         System.Int32
    IL_0017:  ldloc.0     // a
    IL_0018:  ldloc.1     // b
    IL_0019:  mul         
    IL_001A:  box         System.Int32
    IL_001F:  call        System.Console.WriteLine
    IL_0024:  nop         
    IL_0025:  ret
    

    Note that this is not code that can be directly compiled with ilasm, because it doesn't use the full syntax for types and members and also because it does not declare locals.