SoFunction
Updated on 2025-03-07

c# type constructor

The main function is: to set the initialization of static fields in the type. A type constructor does not have to be defined in a class, but there can only be one at most. example:
Copy the codeThe code is as follows:

class SomeType{
static SomeType(){}
}

When the jit compiles a method, the jit compiler will check which types the code refers to. If any type defines a type constructor, the jit compiler will check whether the current AppDomain has executed this type constructor. If it is not, it will be executed. If it has been executed, it will be returned directly and will not be executed again. In a multi-threaded environment, there may be multiple executions of the same method at the same time. CLR hopes that one type constructor in each AppDomain will be executed only once. When calling the type constructor, use a mutex thread synchronization lock to solve this problem.
In a type constructor, only static fields of types can be accessed, and generally only initializes these fields.
Code inline initialization fields:

Copy the codeThe code is as follows:

class SomeType
{
Static int x = 5;
}


Equivalent to

Copy the codeThe code is as follows:

class SomeType
{
Static int x;
Static SomeType()
{
x = 5;
}
}

besides:
Copy the codeThe code is as follows:

class SomeType
{
Static int x = 3;
Static SomeType()
{
x = 5;
}
}

Equivalent to
Copy the codeThe code is as follows:

class SomeType
{
Static int x;
Static SomeType()
{
x = 3;
x = 5;
}
}

Although c# does not allow the value type to be its instantiated field to use inline initialization syntax, static fields are OK. The above can be run if the class is changed to struct.

The main reason is that the value type can define a parameter-free type constructor, but it cannot define a parameter-free type instance constructor.