Sunday, February 10, 2008

Static Constructors in .NET

What is a static constructor?

As part of my job I conduct technical interviews for my company. Till date I have conducted more 500 interviews and one of the stock question in my interview is can constructors be declared static? Most of the time I get a blunt, no, as the answer. Even some argue that one cannot use the static word along with constructors. A very few who say yes are asked further questions on static constructors like what is the difference between a static constructors and normal constructors? For this also I have got lots of answers like static constructors can be called without creating an object, only static variables can be use etc. Some say static constructors are called only once and when I ask when is that once, People don’t have an answer. So I thought I will try to clear some confusion related to static constructors. To know more read on…

Can constructors be declared Static?

Yes.

What is the difference between a static constructor and normal constructors?

As we know Normal constructors are used to initialize class variables whereas static constructors are used to initialize class level static variables. Static constructors cannot access any other objects other than static as similar to static methods. Similar to static method, static constructors are class level and not instance level. Static constructors do not take any access modifiers, like public, private, protected etc. They also don’t take any arguments. Static constructors are called only once.

Static constructors are called only once, when is that once?

Static constructors are called only once throughout the life time of the program, i.e. when the first instance of the class having static constructors is created or when a static member is accessed/used whichever happens first.

Let me explain further, suppose you have a class called StaticConstructor with a static constructor as shown below.

using System;
namespace StaticConstructorDemo
{
class StaticConstructor
{
private static string someText;
private static int counter;
static StaticConstructor()
{
someText = "Static constructor executed. No of times: ";
counter++;
}
public static void PrintSomeText()
{
Console.WriteLine(someText + counter.ToString());
}
}

class MainClass
{
static void Main(string[] args)
{
StaticConstructor sc1 = new StaticConstructor();
StaticConstructor sc2 = new StaticConstructor();
StaticConstructor sc3 = new StaticConstructor();
StaticConstructor.PrintSomeText();
}
}
}

The above code will print “Static constructor executed. No of times: 1”. The reason is static constructor is called only once when the first instance for the class is created i.e. when sc1 is created.

If the above code inside the main method is rewritten like this

class MainClass
{
static void Main(string[] args)
{
StaticConstructor.PrintSomeText();
StaticConstructor sc1 = new StaticConstructor();
StaticConstructor sc2 = new StaticConstructor();
StaticConstructor sc3 = new StaticConstructor();
}
}


The above code will have the same output as the previous code i.e. “Static constructor executed. No of times: 1”. Static constructor is called before the code inside the static method, PrintSomeText(), is executed. As we know static methods can use static members and if a static constructor is not executed then there is every possibility of the system throwing “object reference not set to an instance” error. So static constructors are called before the first instance of the class is created or any static members are accessed/used.

Hope from the above e.g. gives a clear idea. If for any doubt please do post comments.

43 comments:

  1. even though access modifiers are not allowed on static constructors, the runtime has to give static constructors some access level. We know that instance constructors that do not specify an access modifier are private by default, I wonders if this is true for static constructors...

    ReplyDelete
  2. Yes, the same applies to static constructors. Static constructors are private in nature as there is no access specifiers. Even in languages (like Visual C++) where you can give access specifiers to static constructors the best approach recommended is to give private as the access specifier. The reason why this approach is proposed is that static constructors are only meant to be called by CLR.

    ReplyDelete
  3. I am Kasiraja From Karaikudi Your Explanation is very useful to me

    ReplyDelete
  4. Thanks Kasi, I am very happy to hear that my blog was useful.

    ReplyDelete
  5. Really this blog cleared the concept. It will realy help a lot further ...to me atleast

    ReplyDelete
  6. Hi Prashant,
    Its great to hear that this blog helped you to understand the concepts clearly.

    ReplyDelete
  7. can static constructor have Access Specifiers?

    ReplyDelete
  8. No, static constructors cannot have access specifiers. They are private. You can refer my reply to the first comment.

    ReplyDelete
  9. StaticConstructor sc1 = new StaticConstructor();

    They shouldn't allow this syntax in the first place, as static constructor is not meant to be called directly by user. They are not achieving any thing by allowing above.
    -Ravi

    ReplyDelete
  10. Can static constructors have arguments ?

    ReplyDelete
  11. Hi,
    As I have already mentioned in my blog, static constructors don't take any arguments. They also don't have any access specifiers.

    ReplyDelete
  12. Your complete blog post has been stolen and republished here: http://techiemate.blogspot.com/2009/02/static-contructors-in-net.html

    ReplyDelete
  13. Thanks for pointing out this. What can one do about this? There are these kind of unethical professionals who don't have any moral. I have raised my concern to the publisher, if he is an ethical person he will take off the blog else I have to find some other way.

    ReplyDelete
  14. Hi Sandeep,

    What is the access level of the static constructor if I'm declaring my class as public?

    Rgds
    Pradeep

    ReplyDelete
  15. Hi Pradeep,
    It will be private. The same principle applies here as in the case of normal constructors, if you don't give an access specifier they become private.
    Static constructors are meant to be private so thats the reason they don't take any access specifiers. Hope this clears your doubt.

    ReplyDelete
  16. hello , my name is kunjan..
    thankx for guide me

    ReplyDelete
  17. you are the genius .i am the great fan of your articles..The way you have given the explanation for each and every article is really Superbbbbbbbbbbbbbb!

    Regards,
    Senthil.D

    ReplyDelete
  18. Hi Senthil,
    Thanks for your comments.

    ReplyDelete
  19. Hi Sandeep,

    On Page_Load of my application, I query database and store the result in a static variable of a class

    if(Page.IsPostBack)
    {
    /*Code to query DB and store value in a static variable of a class*/
    }

    When I launch the web page then everything works fine.
    However, if I keep the page open for sometime (say 1 hour) and click on any button which access that static variable then I get a error "Object reference not set to an instance of this variable".
    Internet articles says that static variable lifetime is the life of web application.

    But its not working in my case. How to solve it?

    ReplyDelete
  20. In my previous comment, it is:

    if(!Page.IsPostBack)
    {
    /*Code to query DB and store value in a static variable of a class*/
    }

    missed '!'

    ReplyDelete
  21. Sandeep,

    This is really very important information about ststic constructor.. Keep posting such information..

    Happy Coding,
    Kuldeep.

    ReplyDelete
  22. Hey Sandeep ...just could u explain me the Static Constructor and Singleton Class ?? what all common things happen in both the cases ...!!


    Regards,
    Prashant Kutade

    ReplyDelete
  23. Hi Prashant,
    You can refer one of my blogs on singleton here. http://sanddesignpatterns.blogspot.com/2008/02/singleton-design-pattern.html.
    Static constructor gets executed only once where as in singleton you have only one instance of the class which is maintained throughout the life time of the application. There is not much similarity between them. If you can be specific I can clarify more.

    ReplyDelete
  24. Thanks for the information about static constructor.It is too good

    ReplyDelete
  25. Thanks Jamila for the comments.

    ReplyDelete
  26. Yesterday I attend one Interview he ask about the Static Constructor when to use ? is any one knows the answer?

    ReplyDelete
  27. It' simple. When you want to initialize static variables. One cannot access anything other than static variables inside static constructor. Or you can use to write some logic which needs to be executed only once.

    ReplyDelete
  28. StaticConstructor sc1 = new StaticConstructor();

    They shouldn't allow this syntax in the first place, as static constructor is not meant to be called directly by user. They are not achieving any thing by allowing above.

    Not cleared... This is same question asked by RAVI i guess in april 2010.. Please throw some light.

    -Prajakta.

    ReplyDelete
  29. 1. And is this possible to create more than one static constructor of class?

    2. And Do we require static constructor for static class??

    -- Prajkata

    ReplyDelete
  30. please explain que1 with example as u have described in blog.

    ReplyDelete
  31. Hi Prajakta,
    The following syntax StaticConstructor sc1 = new StaticConstructor(); is valid one. Reason is this calls the default constructor and doesn't refer to the static constructor. Static constructors cannot be executed by the user. The framework takes care of executing it only once. () refers to the default constructor.
    One can have only one static constructor.
    There is no restriction like you can have static constructors in static class. About the e.g. you can copy paste the above code and put break points in the static as well as normal constructors. You will see that static constructor will be executed only once but the default constructor will be executed as many times as you create the objects.
    Hope this clarifies your doubt.

    ReplyDelete
  32. Hi Sandeep,

    Really thanks for your explaination.

    Will you plz provide us some useful links which will be helpful to clear dontnet and asp.net concepts which u hv found as a good 1?

    Thanks in advance.

    ReplyDelete
  33. Hi Prajakta,
    I don't have any specific websites, but I do visit MSDN on a daily basis, and read articles there. Also 4guysfromrolla is also a great site. Hansleman.com, scot gutherie' blogs are also good references. Try to enroll to the newsletters of these sites.

    ReplyDelete
  34. why static constructor is needed..?

    ReplyDelete
  35. Simple, static constructors are used to initialize static variables.

    ReplyDelete
    Replies
    1. thank you sir for giving so much helpful information

      Delete
  36. It's amazing. Explanation is too simple and useful.

    ReplyDelete
  37. Hi sandeep ur explanation is superb.its helped me more

    ReplyDelete
  38. Hi Sandeep,

    As you mentioned the use of Static constructor; my question is that why do I need to declare Static Constructor to initialize static variable. I could do the same during declaration of the static member variable. Isn't it ?

    Thanks,
    Mayank

    ReplyDelete
  39. HI Sandeep, can one non static class can have both static and non-static constructors???

    ReplyDelete
  40. Hi Sandeep,

    If i declare static constructor,normal constructor for a class.Which one will be executed first?

    ReplyDelete
  41. Hi Sandeep,

    Your explanation was so clear and simple to understand.

    ReplyDelete

Please provide your valuable comments.