Constructor in depth

There are two types of constructor:Instance Constructor and Type Constructor(or so-called Static Constructor).

Instance Constructor

When use the new key word to create an instance of class, it will do:

  1. Calculate the size of the class, including the sync block and the type object pointer, so that it knows how much memory the instance needs.
  2. Allocate memory.
  3. Call the the constructor,and it will call the constructor of the base class before the current constructor do anything, and so on to the constructor of the Object class.Note that

Constructor is the only way to initialize a instance or a type, We may have seen codes like below:

class SomeClass
{
    private int aField = 5;
    public SomeClass()
    {

    }
}

you may think aField is initialized outside the constructor, but this is just a syntactic trick of c#。The compiler will gen some IL codes to set aField to 5 inside the constructor, AND, if there are more than one constructors, each one will contain that piece of IL initailling codes.

原文地址:https://www.cnblogs.com/lwhkdash/p/6806291.html