Common Type System—Type Initializers


Jump to: navigation, search
Visual C# Tutorials
.NET Framework Tutorials

Common Type System

© 2006 Wiley Publishing Inc.

Type Initializers

There is another style of constructor, called a type constructor. This is commonly referred to as a static or class constructor, or sometimes a type initializer, and permits you to initialize static type information associated with a class. These are named .cctor in the IL, and C# has special syntax for writing them:

class CctorExample
{
   static DateTime classLoadTimestamp;
   static CctorExample()
   {
      classLoadTimestamp = DateTime.Now;
   }
}

Note that this snippet of code is equivalent to the following:

Class CctorExample
{
   static DateTime classLoadTimestamp = DateTime.Now;
}

The C# compiler transforms the latter into the former. An explicit constructor as well as a combination of static field initialzers can appear on the same type. Very much like the previous section on instance field initialization, the compiler will preprend the contents of a type constructor with all field initializations.

Type initializers written in C# have beforefieldinit semantics. This means that the initializers are not guaranteed to run at any specific point, but that they will always be run at least by the time the first access is made for the given type. Access in this context means reading or writing to a static or instance field or a method call to a static or instance method on the type. This permits the CLR to optimize when precisely the initializer is run, delaying it or running it early based on heuristics. Conversely, the default policy is to run initializers precisely when the access is made.

Type constructors run in the context of the thread that caused them to execute. There is logic in runtime to guarantee that circular dependencies among static constructors do not lead to infinite loops. You can explicitly force the execution of type initializations for a target type with the method System.Runtime.CompilerServices. RuntimeHelpers.RunClassConstructor.


Previous_Page_.gif Next_Page_.gif





Personal tools