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

13 Responses to “When is a static constructor in C# called?”

  1. February 23rd, 2006 | 11:17 pm       Reply

    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

  2.   kinywemyawacy
    December 9th, 2009 | 7:26 pm       Reply

    Love to make beats then you should take a look at sonicpro. It works so well, i love all the beats i make.

  3. December 10th, 2009 | 12:28 am       Reply

    Hi!!! msmvps.com is one of the best resourceful websites of its kind. I take advantage of reading it every day. All the best.

  4.   nilesh
    January 6th, 2010 | 3:22 am       Reply

    yes usefull nice one

  5.   praveen
    May 19th, 2010 | 6:16 am       Reply

    good.

  6.   iiwaasnet
    October 10th, 2010 | 12:29 pm       Reply

    public class Foo
    {
    private static readonly Foo instance = new Foo();
    private const int DELTA = 6;
    private static int BASE;
    private readonly int x;

    static Foo()
    {
    BASE = 7;
    }

    private Foo()
    {
    x = BASE + DELTA;
    }

    public static void Main()
    {
    System.Console.Write(Foo.instance.x);
    }
    }

  7.   Katrina
    October 11th, 2011 | 2:11 pm       Reply

    Think about it. Main() is a static method of the class Sample which has a static constructor. By the logic given above, any time you call a static method/property on a class, the static ctor is invoked before the method call. The semantics of a language are never excepted and thus never violated.

  8.   Mukesh
    February 1st, 2012 | 12:26 am       Reply

    thanks, well explained

  9.   ss
    March 28th, 2012 | 12:26 pm       Reply

    Simple and useful for someone like me very new to this. after searching a lot on this subject finally got it right.
    thank you very much.

  10.   SHUBHAM SAXENA
    April 7th, 2012 | 2:23 am       Reply

    Hell Friends ..

    Static Constructors

    This is a new concept introduced in C#. By new here, I mean that it was not available for the C++ developers. This is a special constructor and gets called before the first object is created of the class. The time of execution cannot be determined, but it is definitely before the first object creation – could be at the time of loading the assembly.

    The syntax of writing the static constructors is also damn simple. Here it is:
    Collapse | Copy Code

    public class myClass
    {
    static myClass()
    {
    // Initialization code goes here.
    // Can only access static members here.
    }
    // Other class methods goes here
    }

    Notes for Static Constructors:

    There can be only one static constructor in the class.
    The static constructor should be without parameters.
    It can only access the static members of the class.
    There should be no access modifier in static constructor definition.

    Ok fine, all the above points are fine, but why is it like that? Let us go step by step here.

    Firstly, the call to the static method is made by the CLR and not by the object, so we do not need to have the access modifier to it.

    Secondly, it is going to be called by CLR, who can pass the parameters to it, if required. So we cannot have parameterized static constructor.

    Thirdly, non-static members in the class are specific to the object instance. So static constructor, if allowed to work on non-static members, will reflect the changes in all the object instances, which is impractical. So static constructor can access only static members of the class.

    Fourthly, overloading needs the two methods to be different in terms of methods definition, which you cannot do with Static Constructors, so you can have at the most one static constructor in the class.

    Now, one question raises here, can we have two constructors as:
    Collapse | Copy Code

    public class myClass
    {
    static myClass()
    {
    // Initialization code goes here.
    // Can only access static members here.
    }
    public myClass()
    {
    // Code for the First myDerivedClass Constructor.
    }

    // Other class methods goes here
    }

    This is perfectly valid, though doesn’t seem to be in accordance with overloading concepts. But why? Because the time of execution of the two methods are different. One is at the time of loading the assembly and one is at the time of object creation.

    Shubham Saxena
    Email:shubham.saxena67@gmail.com

  11.   rajeev
    August 14th, 2012 | 6:55 am       Reply

    i know what is static constructor.but i ask when wii it use

  12.   GK
    October 11th, 2012 | 2:14 am       Reply

    can u explain clearly? i couldn’t get it…………………………..

  13.   37316
    May 21st, 2014 | 1:47 am       Reply

    “We must all stop and think first,” Angelina said, most practically. “The bank has been robbed. By this time security men and the police will have sealed off the crime scene. So there is no need for us to rush about in circles flapping our wings.”

Leave a Reply