Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
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.

How to: Define an Interface Static Constructor

An interface 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 interface member is accessed.

For more information on static constructors, see How to: Define Static Constructors in a Class or Struct.

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

interface struct MyInterface {
   static int i;
   static void Test() {
      Console::WriteLine(i);
   }

   static MyInterface() { 
      Console::WriteLine("in MyInterface static constructor");
      i = 99;
   }
};

ref class MyClass : public MyInterface {};

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

   MyInterface ^ mi = gcnew MyClass;
   mi->Test();
}

Output

in MyInterface static constructor
99
99
99

Community Additions

ADD
Show:
© 2015 Microsoft