1. instance Constructor (constructor)
The instance constructor is a special method that allows you to initialize a type of instance to a good state. It is executed when each new instance of the class is created.
The Code is as follows:
Namespace constructordemo1 {internal sealed class myclass // literal class {datetime timeofinstantiation; // declare the field public myclass () // constructor {timeofinstantiation = datetime. now; // initialization field} class program {static void main (string [] ARGs) {myclass MC = new myclass (); // create an object, simultaneous execution class instance constructor }}}
Note: The execution sequence of the constructor is: Member initialization ---> base class constructor call ---> constructor body execution
2. Type constructor
Type constructor, also known as a static constructor. It is used to set the initial status of a type (note that it is not a type instance.
The Code is as follows:
Internal sealed class myclass {Private Static int s_x; // declare static field static myclass () // Type constructor {s_x = 10; // initialize static field }}
Note: the code in the Type constructor can only access static fields of the type, and its common purpose is to initialize these fields.