ECMA-334: 25.1.5 Static constructors in generic classes


Jump to: navigation, search
C# Language Specification
© 2006 ECMA International

25.1.5 Static constructors in generic classes

A static constructor in a generic class is used to initialize static fields and to perform other initialization for each different closed constructed type that is created from that generic class declaration. The type parameters of the generic type declaration are in scope, and can be used, within the body of the static constructor.

A new closed constructed class type is initialized the first time that either:

  • An instance of the closed constructed type is created.
  • Any of the static members of the closed constructed type are referenced.

To initialize a new closed constructed class type, first a new set of static fields (§25.1.4) for that particular closed constructed type is created. Each of the static fields is initialized to its default value (§12.2). Next, the static field initializers (§17.4.5.1) are executed for those static fields. Finally, the static constructor is executed.

Because the static constructor is executed exactly once for each closed constructed class type, it is a convenient place to enforce run-time checks on the type parameter that cannot be checked at compile-time via constraints (§25.7). [Example: The following type uses a static constructor to enforce that the type argument is an enum:

class Gen<T> where T: struct
{
   static Gen() {
      if (!typeof(T).IsEnum) {
         throw new ArgumentException("T must be an enum");
      }
   }
}

end example]


Share this page
  • del.icio.us
  • Facebook
  • Google+
  • StumbleUpon