Friday, August 27, 2010

When is a static constructor in C# called?

A static constructor is invoked by the first of either of the following conditions:

  • Create an instance of the class.
  • Refer any of the static methods of the class.

Confused ? Read ahead...

Example

class Sample

{

   static Sample()

   {

      Console.WriteLine("static constructor called");

   }

   public static void WriteTime()

   {

            Console.WriteLine("Static method called");

   }

   public static void Main(string[] args)

   {

      Sample.WriteTime(); // call 1

      Sample aNewSample = new Sample(); // call 2

   }

}

In the above example, call to the static method WriteTime first calls the static contructor of the class Sample and then the static method is called.

In your Console.Window , you will see:

Line1: static constructor called

Line2: Static method called

 

If after this, you create an instance of the class, the static contructor is not called, as it is only invoked once per class at its first reference (mentioned above). So, call 2

Sample aNewSample = new Sample(); // call 2

will not invoke the static constructor.

 

On the other hand, if there was no call 1 (call 1 is commented out), the static contructor will be invoked when the first object of Sample class is created (a little before the object is created).

 

No comments: