CSharp - Type Creation Static Constructors

Introduction

A static constructor executes once per type, rather than once per instance.

A type can define only one static constructor, and it must be parameterless and have the same name as the type:

class Test
{
       static Test() { 
           Console.WriteLine ("Type Initialized"); 
       }
}

The runtime automatically invokes a static constructor just before the type is being used.

Two things trigger this:

  • Instantiating the type
  • Accessing a static member in the type

The only modifiers allowed by static constructors are unsafe and extern.