static variables initialization

1.-3.You cannot exactly know when it happens and so you cannot depend on it. A static constructor will give you a little control what happens when it get called.

public class UtilityClass
{
  //
  // Resources
  //

  // r1 will be initialized by the static constructor
  static Resource1 r1 = null;

  // r2 will be initialized first, as static constructors are 
  // invoked after the static variables are initialized
  static Resource2 r2 = new Resource2();

  static UtilityClass()
  {
    r1 = new Resource1();
  }

  static void f1(){}
  static void f2(){}
}

4.Static constructors are slow

The exact timing of static constructor execution is implementation-dependent, but is subject to the following rules:

  • The static constructor for a class
    executes before any instance of the
    class is created.
  • The static constructor for a class
    executes before any of the static
    members for the class are
    referenced.
  • The static constructor for a class
    executes after the static field initializers (if any) for the class.
  • The static constructor for a class
    executes, at most, one time during
    a single program instantiation.
  • The order of execution between two
    static constructors of two
    different classes is not specified.

Leave a Comment

404 Not Found

Not Found

The requested URL was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.