Static Constructors
Static constructor is used to initialize the static data members of the class. Static constructor is only called once while creation of the first instance of the class. After that, no instance of a class will call the static constructor. You can also use static constructor to execute some code of the class which must be executed only once.
public class Person
{
static Person()
{
//Static Members
}
} |
In inheritance, the calling of the constructor starts from the parent class.
Let's see how to use these constructors -
static void Main(string[] args)
{
Person p1 = new Person();//This will call Default Constructor
Person p2 = new Person("Pravin", "D");//This will call two parameterized Constructor
Person p3 = new Person(p2);//This will call Copy Constructor
} |
It is worth mentioning that you can also create a private constructor, which is generally used in classes that contain static members only. If you create a private constructor, you cannot create an instance of a class.
class Person
{
// Private Constructor:
private Person() { }
...
} |
I hope you got an idea of the different types of Constructors in C#. This question is frequently asked in interviews, so make sure to revise it before heading for your interview.