Why is the .ctor() created when I compile C# code into IL?

prosseek picture prosseek · Aug 29, 2011 · Viewed 10.5k times · Source

With this simple C# code, I run csc hello.cs; ildasm /out=hello.txt hello.exe.

class Hello
{
    public static void Main()
    {
        System.Console.WriteLine("hi");
    }
}

This is the IL code from ildasm.

.class private auto ansi beforefieldinit Hello
       extends [mscorlib]System.Object
{
  .method public hidebysig static void  Main() cil managed
  {
    .entrypoint
    // Code size       13 (0xd)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ldstr      "hi"
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ret
  } // end of method Hello::Main

  .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 Hello::.ctor

} // end of class Hello

What's the use of .method public instance void .ctor() code? It doesn't seem to do anything.

Answer

BoltClock picture BoltClock · Aug 29, 2011

It's the default parameterless constructor. You're correct; it doesn't do anything (besides passing on to the base Object() constructor, which itself doesn't do anything special either anyway).

The compiler always creates a default constructor for a non-static class if there isn't any other constructor defined. Any member variables are then initialized to defaults. This is so you can do

new Hello();

without running into errors.