static Statement

Declares a new class initializer inside a class declaration.

static identifier {
   [body]
}

Arguments

  • identifier
    Required. The name of the class that contains the initializer block.

  • body
    Optional. The code that comprises the initializer block.

Remarks

A static initializer is used to initialize a class object (not object instances) before its first use. This initialization occurs only once, and it can be used to initialize fields in the class that have the static modifier.

A class may contain several static initializer blocks interspersed with static field declarations. To initialize the class, all the static blocks and static field initializers are executed in the order in which they appear in the class body. This initialization is performed before the first reference to a static field.

Do not confuse the static modifier with the static statement. The static modifier denotes a member that belongs to the class itself, not any instance of the class.

Example

The following example shows a simple class declaration in which the static initializer is used to perform a calculation that only needs to be done one time. In this example, a table of factorials is calculated once. When factorials are needed they are read from the table. This approach is faster than calculating factorials recursively if large factorials are needed many times in the program.

The static modifier is used for the factorial method.

class CMath {
   // Dimension an array to store factorial values.
   // The static modifier is used in the next two lines.
   static const maxFactorial : int = 5;
   static const factorialArray : int[] = new int[maxFactorial];

   static CMath {
      // Initialize the array of factorial values.
      // Use factorialArray[x] = (x+1)!
      factorialArray[0] = 1;
      for(var i : int = 1; i< maxFactorial; i++) {
         factorialArray[i] = factorialArray[i-1] * (i+1);
      }
      // Show when the initializer is run.
      print("Initialized factorialArray.");
   }

   static function factorial(x : int) : int {
      // Should have code to check that x is in range.
      return factorialArray[x-1];
   }
};

print("Table of factorials:");

for(var x : int = 1; x <= CMath.maxFactorial; x++) {
   print( x + "! = " + CMath.factorial(x) );
}

The output of this code is:

Table of factorials:
Initialized factorialArray.
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120

Requirements

Version .NET

See Also

Reference

class Statement

static Modifier