What is difference between constructor and static constructor
What is difference between constructor and static constructor and what is the benefit of using static constructor.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Aug 29, 2012, 4:24 AM EDT
The benefit of having one is that you don't then need to remember to call a static method to do class initialization, which could cause problems if you forget to do so.
Jignesh TrivediRank #16 · 50.3K reputationPosted Aug 29, 2012, 4:24 AM EDT
Static constructor will be called first time when the class is referenced. Static constructor is used to initialize static members of the class.
In the non static class the private or public constructor will not be called. Static members will not be initialized either by private or public constructor.
Please refer
http://www.c-sharpcorner.com/uploadfile/AmitSaxena/constructor-vs-static-constructor/
http://msdn.microsoft.com/en-us/library/k9x6w0hc%28v=vs.80%29.aspx
hope this will help you.
Akkiraju IvaturiRank #473 · 5.3K reputationPosted Aug 29, 2012, 4:44 AM EDT
I am going to take the example from MSDN for the same and extend it to understand it better.
Public class Bus
{
static int wheels;
static Bus()
{
wheels = 4;
console.writeline("Each bus must have 4 wheels");
}
public void Drive()
{
Console.WriteLine(wheels.ToString() + "wheels drive the bus");
}
}
static void Main(...)
{
Bus b=new Bus();
b.Drive();
Bus anotherbus = Bus();
anotherbus.Drive();
}
Any number of object instances will have same number of wheels. Otherwise it is not a bus. In this example static constructor was called only once and the life time of the property wheels is set as 4 for the firstime and no object of this class can change the number of wheels. If you have any scenario like this, we must be using static constructor.
Hope this clears your question. Any questions, feel free to ask.
}