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; class MainClass |
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 |
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.
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...
ReplyDeleteYes, 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.
ReplyDeleteI am Kasiraja From Karaikudi Your Explanation is very useful to me
ReplyDeleteThanks Kasi, I am very happy to hear that my blog was useful.
ReplyDeleteReally this blog cleared the concept. It will realy help a lot further ...to me atleast
ReplyDeleteHi Prashant,
ReplyDeleteIts great to hear that this blog helped you to understand the concepts clearly.
can static constructor have Access Specifiers?
ReplyDeleteNo, static constructors cannot have access specifiers. They are private. You can refer my reply to the first comment.
ReplyDeleteStaticConstructor sc1 = new StaticConstructor();
ReplyDeleteThey 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
Can static constructors have arguments ?
ReplyDeleteHi,
ReplyDeleteAs I have already mentioned in my blog, static constructors don't take any arguments. They also don't have any access specifiers.
Your complete blog post has been stolen and republished here: http://techiemate.blogspot.com/2009/02/static-contructors-in-net.html
ReplyDeleteThanks 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.
ReplyDeleteHi Sandeep,
ReplyDeleteWhat is the access level of the static constructor if I'm declaring my class as public?
Rgds
Pradeep
Hi Pradeep,
ReplyDeleteIt 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.
hello , my name is kunjan..
ReplyDeletethankx for guide me
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!
ReplyDeleteRegards,
Senthil.D
Hi Senthil,
ReplyDeleteThanks for your comments.
Hi Sandeep,
ReplyDeleteOn 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?
In my previous comment, it is:
ReplyDeleteif(!Page.IsPostBack)
{
/*Code to query DB and store value in a static variable of a class*/
}
missed '!'
Sandeep,
ReplyDeleteThis is really very important information about ststic constructor.. Keep posting such information..
Happy Coding,
Kuldeep.
Thanks Kuldeep.
ReplyDeleteHey Sandeep ...just could u explain me the Static Constructor and Singleton Class ?? what all common things happen in both the cases ...!!
ReplyDeleteRegards,
Prashant Kutade
Hi Prashant,
ReplyDeleteYou 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.
Thanks for the information about static constructor.It is too good
ReplyDeleteThanks Jamila for the comments.
ReplyDeleteYesterday I attend one Interview he ask about the Static Constructor when to use ? is any one knows the answer?
ReplyDeleteIt' 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.
ReplyDeleteStaticConstructor sc1 = new StaticConstructor();
ReplyDeleteThey 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.
1. And is this possible to create more than one static constructor of class?
ReplyDelete2. And Do we require static constructor for static class??
-- Prajkata
please explain que1 with example as u have described in blog.
ReplyDeleteHi Prajakta,
ReplyDeleteThe 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.
Hi Sandeep,
ReplyDeleteReally 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.
Hi Prajakta,
ReplyDeleteI 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.
why static constructor is needed..?
ReplyDeleteSimple, static constructors are used to initialize static variables.
ReplyDeletethank you sir for giving so much helpful information
DeleteIt's amazing. Explanation is too simple and useful.
ReplyDeleteHi sandeep ur explanation is superb.its helped me more
ReplyDeleteHi Sandeep,
ReplyDeleteAs 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
HI Sandeep, can one non static class can have both static and non-static constructors???
ReplyDeleteHi Sandeep,
ReplyDeleteIf i declare static constructor,normal constructor for a class.Which one will be executed first?
Hi Sandeep,
ReplyDeleteYour explanation was so clear and simple to understand.
Really awesome blog! Your blog is really useful for me and Thanks for sharing this informative blog
ReplyDeletedot net online training
https://onlineitguru.com/dot-net-online-training-placement.html