SoFunction
Updated on 2025-03-08

c# value type instance constructor

The reference type contains the value type field. After the reference type is initialized, the value type will be initialized to 0 and Null by default.
CLR allows to define constructors for value types, but the constructor calls must be explicitly written to call them.

CLR does not allow defining parameterless constructors for value types. Only parameter constructors can be defined, and all fields in the constructor must be assigned values ​​to each of the fields in the value type, otherwise an error will be reported.

Although there is no parameterless constructor in C#, you can use this syntax to initialize internal fields:

StructType st = new StructType();//Initialize 0 or null for internal fields

Therefore, the reference writing method for defining parameter constructors:
Copy the codeThe code is as follows:

public StructType(int x){ //Define parameter constructor
this = new StructType();//Initialize all fields to 0 or Null
m_x = x;//Cover the m_x field with parameter x, m_x has been initialized to 0 by the previous sentence
}