Tuesday, March 13, 2007

"beforeFieldInit"

"beforeFieldInit" is a special flag marked by compiler to the types which doesn't have static constructor.
This special flag tells "calling a static method does not force the system to initialize the type." Means that calling a static method does not make sure the static variables are initialized in the type.
public class ResourceClass
{
private static StreamWriter sw = new StreamWriter();
public static StreamWriter GetInstance()
{
return sw;
}
}
In the above type it is not guranteed that when you call GetInstance the static variable "sw" would be created. Because of the reason the class is marked as "beforeFieldInit".
public class ResourceClass
{
private static StreamWriter sw = new StreamWriter();
static ResourceClass() { };

public static StreamWriter GetInstance()
{
return sw;
}

}

In the above type it is guranteed that when you call GetInstance the static variable "sw" would be created. Because of the reason the class contains "static constructor".
Properties of static constructor
  • Static constructors are not inherited, and cannot be called directly.
The exact timing of static constructor execution is implementation-dependent, but is subject to the following rules:
  1. The static constructor for a class executes before any instance of the class is created.
  2. The static constructor for a class executes before any of the static members for the class are referenced.
  3. 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.
  4. The order of execution between two static constructors of two different classes is not specified.
But CLI does insist that all of the field variables will be initialized as soon as one of the static fields is accessed. So if we are depending on some side effects based on static variable initialization, then we may be waiting for a long time that to happen.