Some Interesting information we should know about STATIC Constructor
1. Can we use the static constructor in class?
2. Why we are using static constructor?
Generally we use the static constructor to initialize any static data
3. When will static constructor get call?
The Static constructor is called before creating first instance of the class.
4. How many static constructors will be in the class?
There can be only one static constructor in the class.
5. Can we send parameters in static constructor?
The static constructor should be without parameters.
6. What is the restriction in it?
It can only access the static members of the class.
7. Can we add access modifies in static constructor?
There should be no access modifier in static constructor definition.
8. How can we call static constructor?
Static constructor is called automatically. When the user trying to create first instance or if the user trying to access the class. It will call automatically
9. Is Static constructor Invoke second time?
No, When we declared constructor as static it will be invoked only once for any number of instances of the class.
public class myClass
// Initialization code goes here.
// Can only access static members here.
// Code for the First myDerivedClass Constructor.
// Other class methods goes here
Good collection of points regarding static constructor. Let me add few lines.
1.Static constructor is executed only once when the class is loading in to the memory.
2.Static constructor can access only static variables.
public string s="static constructor example";
public sample3() // normal constructor
MesssageBox.Show("Am from normal constructor");
static sample3() // static constructor
MessageBox.Show("Am from static constructor");
sample3 obj=new sample3();
sample3 obj1=new sample3();
I want to add one more points.
Static constructor is used to initialize static member but real use is when we want log some thing before executing the class. It is also used for loading com library .