c type constructor

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

The main function is to set the initialization of a static field in a type. Type constructors are not necessarily defined in a class, but there can be no more than one. Ex. :
 
class SomeType{ 
static SomeType(){} 
} 

When the jit compiler compiles a method, it looks at what types the code references. If any type defines a type constructor, the jit compiler checks to see if the current AppDomain has executed the type constructor. If it has not, it executes. If it has, it returns and does not execute again. In a multi-threaded environment, there may be more than one execution of the same method at the same time. CLR wants one type constructor in each AppDomain to execute only once.
Only the static fields of the type can be accessed in the type constructor; 1 simply initializes these fields.
Code inline initialization field:

 
class SomeType 
{ 
Static int x = 5; 
} 


Is equivalent to

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

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

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

While c# does not allow the value type to use inline initialization syntax for its instantiated fields, static fields do, and the class to struct1 example above will work.

The main reason is that a value type can define an argument free type constructor, but not an argument free type instance constructor.

Related articles: