C# .Net Tutorial Intermediate Language – MSIL

Microsoft Intermediate Language (MSIL) is a platform independent language that gets compiled into platform dependent executable file or dynamic link library. It means .NET compiler can generate code written using any supported languages and finally convert it to the required machine code depending on the target machine.

To get some clarity in this language we need to write some code. In this tutorial we?ll use a very simple piece of source code in C# .Net. Now we need to compile this code using csc command in Microsoft .NET on the command line. To do this, please type next string: csc ILSample.cs. After it compiler will create an executable file named ILSample.exe.

After this type the command called ILDasm. It will open application called Intermediate Language Disassembler. In file menu choose open and find our executable file.This application opens our assembly showing all structural units viz., classes, methods, data fields and all global and local application data. Now if you click on the method it shows code in intermediate language. This code is most like at language with independent set of instructions.


public double GetVolume()
{
double volume = height*width*thickness;
if(volume<0)
return 0;
return volume;
}

You can get the strings of Microsoft Intermediate Language code using ILDasm:


.method public hidebysig instance float64
GetVolume() cil managed
{
// Code size 51 (0x33)
.maxstack 2
.locals init ([0] float64 volume,
[1] float64 CS$00000003$00000000)
IL_0000: ldarg.0
IL_0001: ldfld float64 OOP.Aperture::height
IL_0006: ldarg.0
IL_0007: ldfld float64 OOP.Aperture::width
IL_000c: mul
IL_000d: ldarg.0
IL_000e: ldfld float64 OOP.Aperture::thickness
IL_0013: mul
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: ldc.r8 0.0
IL_001f: bge.un.s IL_002d
IL_0021: ldc.r8 0.0
IL_002a: stloc.1
IL_002b: br.s IL_0031
IL_002d: ldloc.0
IL_002e: stloc.1
IL_002f: br.s IL_0031
IL_0031: ldloc.1
IL_0032: ret
} // end of method Aperture::GetVolume

To clearly understand that IL really is immediately language you should write the same code in VB .NET and look at these two sources in IL. These methods will be almost identical.

The main advantages of IL are:

  1. IL isn?t dependent on any language and there is a possibility to create applications with modules that were written using different .NET compatible languages.
  2. Platform independence – IL can be compiled to different platforms or operating systems.

The sample code for this article is available here.