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

你说的曾经没有我的故事 提交于 2019-11-30 17:35:54

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!