c value type instance constructor

  • 2020-05-07 20:19:14
  • OfStack

The reference type contains the value type field, and after the reference type is initialized, the value type is initialized to 0 and Null by default.
CLR allows you to define constructors for value types, but calls to constructors must explicitly write code to call them.

CLR does not allow you to define parameter free constructors for value types. Only a parameter constructor can be defined, and all fields in the value type must be assigned in the constructor, otherwise an error is reported.

There is no argument free constructor in c#, but you can use this syntax to initialize fields inside:

StructType st = new StructType(); // initializes 0 or null for the internal field

Therefore, the reference for defining the parameter constructor is:
 
public StructType(int x){ // Defines a parameter constructor  
this = new StructType();// Initialize all the fields to 0 or Null 
m_x = x;// With the parameters x cover m_x Fields, m_x Has been initialized to by the previous sentence 0 
} 

Related articles: