Some Interesting information we should know about STATIC Constructor
All of us know or heard about STATIC Constructor.
But if anybody asked some twisting question about STATIC Constructor. Definitely we will struck at least few seconds.
I gathers some Interesting information about STATIC Constructor and posted.
Some Interesting information we should know about STATIC Constructor
1. Can we use the static constructor in class?
Yes
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.Syntax
public class myClass
{
static myClass()
{
// Initialization code goes here.
// Can only access static members here.
}
public myClass()
{
// Code for the First myDerivedClass Constructor.
}
// Other class methods goes here
}
Hi Nathan.
Good collection of points regarding static constructor. Let me add few lines.
Static constructor:
1.Static constructor is executed only once when the class is loading in to the memory.
2.Static constructor can access only static variables.
class sample3
{
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");
}
}
button click
{
sample3 obj=new sample3();
sample3 obj1=new sample3();
}