Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

il

csc

ildasm

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.

like image 902
prosseek Avatar asked Aug 29 '11 20:08

prosseek


2 Answers

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.

like image 152
BoltClock Avatar answered Oct 27 '22 03:10

BoltClock


This is covered in section 10.11.4 of the C# language spec

If a class contains no instance constructor declarations, a default instance constructor is automatically provided. That default constructor simply invokes the parameterless constructor of the direct base class

Here Hello has no defined constructor hence the compiler inserts the default do nothing constructor which just calls the base / object version

like image 33
JaredPar Avatar answered Oct 27 '22 02:10

JaredPar