Constructors are the special member function/method of a class having the same name as the class.
Constructors cannot be invoked by the object of the class, it automatically runs whenever the object of the class gets created. The more the objects of the class the more the constructor will be invoked.
Constructor does not have any return type.
Types of Constructors,
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
1. Default constructor:
Default constructor has the same name as the class and does not have any parameters. It also initializes the numeric values as zero and strings as null.
using System;
namespace Learn2Done{
class ConstructorDemo{
// A constructor is made which has the same name as the class.
public ConstructorDemo(){
// This message will be shown when object of class is created.
Console.WriteLine("Hi! Constructor is invoked.");
}
}
class Program{
static void Main(string[] args)
{
// Message from Constructor will be shown as object is created.
ConstructorDemo obj = new ConstructorDemo();
}
}
}
using System;
namespace DefaultConstructor{
class DefaultConst{
int num;
string str;
// Default Constructor example.
DefaultConst(){
Console.WriteLine("Default Constructor is invoked.");
}
}
class Program{
static void Main(string[] args)
{
// Message from Constructor will be shown as object is created.
DefaultConst obj = new DefaultConst();
}
}
2. Parameterized Constructor:
Parameterized constructor has parameters passed onto the constructors. Arguments are passed while creating the object of the class which is passed onto the constructor.
using System;
namespace ParameterizedConstructor{
class ParameterizedConst{
public int num;
string str;
// Parameterized Constructor example.
ParameterizedConst(int n){
this.num = n; Console.WriteLine("Parameterized ParameterizedConst is invoked.");
}
}
class Program{
static void Main(string[] args)
{
// Message from Constructor will be shown as object is created.
ParameterizedConst obj = new ParameterizedConst(10);
// Output will be 10. Console.WriteLine(obj.num);
}
}
3. Copy Constructor:
Copy constructor takes an object as a parameter and initialize a new instance with values of existing instance.
using System;
namespace CopyConstructor{
class CopyConst{
public int num;
string str;
// Copy Constructor example.
CopyParameterizedConst(CopyParameterizedConst c)
{
num = c.num;
}
// Copy Constructor example.
CopyParameterizedConst(int n){
this.num = n; Console.WriteLine("Copy CopyConst is invoked.");
}
}
class Program{
static void Main(string[] args)
{
// Message from Constructor will be shown as object is created.
CopyParameterizedConst obj = new CopyParameterizedConst(10);
// Output will be 10.
Console.WriteLine(obj.num);
}
}