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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Akkiraju IvaturiPosted Aug 29, 2012, 8:44 AM
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.
}
Jignesh TrivediPosted Aug 29, 2012, 8:24 AM
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.
VulpesPosted Aug 29, 2012, 8:24 AM
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.