Constructor types with example programs in C#.NET

A special method of the class that will be automatically invoked when an instance of the class is created is called as constructor.

Constructors can be classified into 5 types

Default Constructor

Parameterized Constructor

Copy Constructor

Static Constructor

Private Constructor

Default Constructor : A constructor without any parameters is called as default constructor. Drawback of default constructor is every instance of the class will be initialized to same values and it is not possible to initialize each instance of the class to different values.

Parameterized Constructor : A constructor with at least one parameter is called as parameterized constructor. Advantage of parameterized constructor is you can initialize each instance of the class to different values.

Copy Constructor : A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance.

Example for Copy Constructor

using System;

namespace ProgramCall
{

classTest2
{

int A, B;

public Test2(int X, int Y)
{
A = X;
B = Y;
}

//Copy Constructorpublic Test2(Test2 T)
{
A = T.A;

B = T.B;
}

publicvoid Print()
{

Console.WriteLine("A = {0}\tB = {1}", A, B);
}

}

classCopyConstructor
{staticvoid Main()
{

Test2 T2 = newTest2(80, 90);

//Invoking copy constructorTest2 T3 = newTest2(T2);

T2.Print();
T3.Print();

Console.Read();
}
}
}

Output

A = 80 B = 90
A = 80 B = 90

Static Constructor : You can create a constructor as static and when a constructor is created as static, it will be invoked only once for any number of instances of the class and it is during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.

Private Constructor : You can also create a constructor as private. When a class containsat least one private constructor, then it is not possible to create an instance for the class. Private constructor is used to restrict the class from being instantiated when it contains every member as static.