开发者

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

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.Objec开发者_如何学Pythont::.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.


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.


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


A class for which you don't define a constructor gets an implicit public default constructor.

public MyClass()
  :base()
{
}

This only works if the base class has an accessible parameterless constructor.


class Hello inherits object, the default generated constructor simply calls the constructor of class object.


I would imagine the specification stipulates that since your class itself is not static or abstract, it must expose a default parameterless constructor. This way, other users of whatever library or PE you build can instantiate a copy of your class.

If it didn't have a .ctor, it could be construed as having a private .ctor, I suppose. It's generally pretty vague. But logically, you're right, there is no need for the .ctor in this instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜