Static Constructors
Collapse the table of content
Expand the table of content
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

Static Constructors

A static constructor is used to initialize a class. It is called automatically to initialize the class before the first instance is created or any static members are referenced. It is declared using the following form:

[attributes] static identifier( ) { constructor-body }

where:

attributes (Optional)
Additional declarative information. For more information on attributes and attribute classes, see C# Attributes.
identifier
The identifier is the same as the class name.
constructor-body
The block that contains the statements that initialize the class.

Remarks

A static constructor does not take access modifiers or have parameters.

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

A static constructor cannot be called directly.

The user has no control on when the static constructor is executed in the program.

A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

Example

In this example, the class MyClass has a static constructor and one static member, MyMethod(). When MyMethod() is called, the static constructor is invoked to initialize the class.

// StaticCtor1.cs
using System;
class MyClass
{
   // Static constructor:
   static MyClass() 
   {
      Console.WriteLine("The static constructor invoked.");
   }

   public static void MyMethod()
   {
      Console.WriteLine("MyMethod invoked.");
   }
}

class MainClass
{
   static void Main() 
   {
      MyClass.MyMethod();
   }
}

Output

The static constructor invoked.
MyMethod invoked.

For more information and examples of static constructors, see 1.7.10 Static constructors and 10.11 Static constructors.

See Also

static | Constructors and Destructors | Class Constructors

Show:
© 2016 Microsoft