Export (0) Print
Expand All

How to: Define Static Constructors in a Class or Struct

A CLR type, such as a class or struct, can have a static constructor, which can be used to initialize static data members. A static constructor will be called at most once, and will be called before the first time a static member of the type is accessed.

An instance constructor will always run after a static constructor.

The compiler cannot inline a call to a constructor if the class has a static constructor. The compiler cannot inline a call to any member function if the class is a value type, has a static constructor, and does not have an instance constructor. The common language runtime may inline the call, but the compiler cannot.

A static constructor should be defined as a private member function, as the static constructor is only meant to be called by the common language runtime.

For more information on static constructors, see How to: Define an Interface Static Constructor .

// mcppv2_ref_class6.cpp
// compile with: /clr
using namespace System;

ref class MyClass {
private:
   static int i = 0;

   static MyClass() {
      Console::WriteLine("in static constructor");
      i = 9;
   }

public:
   static void Test() {
      i++;
      Console::WriteLine(i);
   }
};

int main() {
   MyClass::Test();
   MyClass::Test();
}

Output

in static constructor
10
11

Community Additions

ADD
Show:
© 2014 Microsoft