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).

Published Mon, Feb 20 2006 20:19 by Vipul Patel
Filed under:

Comments

# re: When is a static constructor in C# called?

Really usefull one..Patel
I heard about static methods..but static constructor...absolutly new to me.But i want to know how this static constructor called....I have placed a breakpoint in s.contructor as well as in Main method. its hitting S.construtor before the main method..?
How this possible..? for any program main is the entry point right..?
please write about this..

Maheshkumar.R
mfcmahesh@hotmail.com

Thursday, February 23, 2006 11:17 PM by MaheshKumar.R

Leave a Comment

(required) 
(required) 
(optional)
(required)