HelloWorld in MSIL

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search

The following HelloWorld program was written by hand in MSIL and assembled using the Intermediate Language Assembler (ilasm):

Example (informative):
.assembly extern mscorlib {}
.assembly hello {}
.method static public void main() cil managed
{ 
  .entrypoint
  .maxstack 1
  ldstr "Hello, World!"
  call void [mscorlib]System.Console::WriteLine(class System.String)
  ret
}

The .assembly extern declaration references the external assembly mscorlib which defines System.Console. The next .assembly declaration declares the assembly name for this program. Assemblies are the deployable unit of executable content for the Common Language Infrastructure (CLI). The .method declaration defines the global main method. Braces enclose the body of the method. The first line of the body—.entrypoint—indicates that this method is the assembly entry point. The second line of the body—.maxstack—specifies that it requires at most one stack slot.

The main method contains three assembler instructions. The ldstr (load string) instruction pushes the string constant "Hello, World!" onto the stack. The call instruction invokes System.Console::WriteLine with the string argument. call instructions include the full signature of the called method. String literals in CIL are instances of the standard class System.String. Finally, the ret instruction returns from the main method.


The following HelloWorld program is written in C#:

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

Compare the handwritten MSIL version with the following HelloWorld program assembled from the C# version using Visual Studio .NET and viewed in Intermediate Language Disassembler (ildasm):

.class private auto ansi beforefieldinit ConsoleApplication1.HelloWorld
       extends [mscorlib]System.Object
{
} // end of class ConsoleApplication1.HelloWorld


.method public hidebysig specialname rtspecialname 
        instance void  .ctor() cil managed
{
  // Code size       7 (0x7)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
  IL_0006:  ret
} // end of method HelloWorld::.ctor


.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       13 (0xd)
  .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 HelloWorld::Main

Personal tools