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
}


Comments

Author: Sridhar Thota06 Dec 2015 Member Level: Gold   Points : 4

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();
}

Author: rajesh19 Dec 2015 Member Level: Bronze   Points : 2

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 .



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: