C# - Common Language Intermediate (CIL)

    1 Votes

The common language intermediate is also known as Microsoft Intermediate Language (MSIL). It plays an important role in .Net Framework. It acts as the intermediate language which exists between source code and machine code at the time of compilation. The source code of the .Net application can be written in any language such as VB.Net, ASP.Net etc.

During compilation, source code will be converted into CIL and then it will be converted into machine code by the JIT compiler. Now before going into deep further let us have a look on example in C#:

using System;
namespace ConsoleApplication1
   class HelloWorld
      static void Main (string[] args)
         Console.WriteLine ("Hello World");
         Console.ReadKey ( );

Now the Hello World in CIL:

 .assembly extern mscorlib
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                        
  .ver 4:0:0:0
.assembly HelloWorld
 ----lines omitted
.module HelloWorld.exe
.class private auto ansi beforefieldinit HelloWorld.Program
       extends [mscorlib]System.Object
 .method private hidebysig static void  Main(string[] args) cil managed
        .maxstack  8
    IL_0000:  nop
    IL_0001:  ldstr      "Hello World"
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ret
  } // end of method Program::Main
  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  ret
  } // end of method Program::.ctor

} // end of class HelloWorld.Program

In the above code you will notice some names as CIL tokens with prefix .(dot). Like .assembly, .namespace, .class, .method and so on, they all are known as CIL directives. The CIL attributes tell that the tokens which are to be used along with CIL directive and it also describe how the CIL directive should be processed. For example: public, extends, implements.

The CIL Opcodes or the operation code is the tokens that are used to build the type implementation logic. For example: add, sub, mul, div, call, etc. They are basically the binary codes (0x01) and they have instruction for each binary code which helps the developer to understand, debug and write code directly in intermediate language. Some of the examples are:

Binary OpcodeInstruction
0x00 Nop
0x01 Break
0x02 Idarg.0
0x03 Idarg.1
0x72 Idstr
0x73 Newobj
0x7A Throw
0x8C box