static Constructors


static Constructors

As opposed to an instance constructor, a static constructor of a class cannot be called explicitly in the source code. Instead, it is called automatically by the runtime sometime between the start of the program and the instantiation of the first object of the class. The static constructor is declared by writing the static keyword in front of the name of the class and by ending the line with empty parentheses (see Syntax Box 13.3). The statements are positioned in a block after this header.

There are a couple of notable differences between the declaration of a static constructor and an instance constructor. First, because the static constructor can only be accessed by the runtime, it makes no sense to specify an access modifier. Second, because the runtime wouldn't know which arguments to provide, no formal parameters can be specified.

The static constructor is not only typically used to initialize static variables (see the example in Syntax Box 13.3), but also used to perform other tasks that must be done once before the first instance of a class is created.

Syntax Box 13.3 The static Constructor

 static <Constructor_identifier> ( ) {     <Statements> } 


  • The <Constructor_identifier> must be identical to the name of the class in which the static constructor resides.

  • No arguments can be specified for the static constructor.

  • No access modifiers can be specified for the static constructor.


 class Fish {     private static int numberOfFishCreated;     static Fish()     {         numberOfFishCreated = 0;     }     ... } 



The call to the static constructor of a class could take place right after the start of the program, just before the creation of the first instance of the class, or somewhere in between. It all depends on the runtime's frame of mind. Because of this timing uncertainty, you should not let the static constructor contain any statements that are sensitive to timing.


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata © 2008-2017.
If you may any questions please contact us: