NGWS SDK Documentation  

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

10.12 Static constructors

Static constructors implement the actions required to initialize a class. Static constructors are declared using static-constructor-declarations:

static-constructor-declaration:
attributesopt static identifier ( ) block

A static-constructor-declaration may include set of attributes (§17).

The identifier of a static-constructor-declarator must name the class in which the static constructor is declared. If any other name is specified, an error occurs.

The block of a static constructor declaration specifies the statements to execute in order to initialize the class. This corresponds exactly to the block of a static method with a void return type (§10.5.7).

Static constructors are not inherited.

Static constructors are invoked automatically, and cannot be invoked explicitly. The exact timing and ordering of static constructor execution is not defined, though several guarantees are provided:

The example

using System;
class Test
{
   static void Main() {
      A.F();
      B.F();
   }
}
class A
{
   static A() {
      Console.WriteLine("Init A");
   }
   public static void F() {
      Console.WriteLine("A.F");
   }
}
class B
{
   static B() {
      Console.WriteLine("Init B");
   }
   public static void F() {
      Console.WriteLine("B.F");
   }
}

could produce either the output:

Init A
A.F
Init B
B.F

or the output:

Init B
Init A
A.F
B.F

because the exact ordering of static constructor execution is not defined.

The example

using System;
class Test
{
   static void Main() {
      Console.WriteLine("1");
      B.G();
      Console.WriteLine("2");
   }
}
class A
{
   static A() {
      Console.WriteLine("Init A");
   }
}
class B: A
{
   static B() {
      Console.WriteLine("Init B");
   }
   public static void G() {
      Console.WriteLine("B.G");
   }
}

is guaranteed to produce the output:

Init A
Init B
B.G

because the static constructor for the class A must execute before the static constructor of the class B, which derives from it.