There are four types of constructors –
- Default constructor
- Parameterised constructor
- Copy constructor
- Static constructor
1. Default constructor –
The constructor, which is created by the compiler, is called the default constructor.
It is always a parameterless constructor.
// Default constructor
using System;
class CallOfCode
{
//Initialise with default value
int num = 0;
public CallOfCode()
{
Console.WriteLine("Constructor Called");
}
public static void Main()
{
// Invoke default constructor
Geeks geek1 = new Geeks();
}
}
2. Parameterised constructor –
The constructor that takes one or more parameters is called a parameterised constructor.
It is created by a programmer, NOT provided by the compiler.
// Parameterized Constructor
using System;
class CallOfCode {
// store name value
String n;
// store Id
int i;
CallOfCode(String n, int i)
{
this.n = n;
this.i = i;
}
public static void Main()
{
// It will invoke parameterised
CallOfCode o = new CallOfCode("COC", 11);
Console.WriteLine("Name = " + o.n + " Id = " + o.i);
}
}
3. Copy constructor –
The copy constructor is a special type of constructor in C# that is used to create a new object by copying the contents of an existing object of the same class. It takes an object of the same class as its parameter and initialises the new object with the values of the existing object.
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
// Copy constructor
public Person(Person other)
{
Name = other.Name;
Age = other.Age;
}
}
// Usage
Person person1 = new Person("John", 30);
Person person2 = new Person(person1); // Calls the copy constructor
4. Static constructor –
A static constructor is a special type of constructor in C# that is used to initialize static fields of a class. Static fields are variables that belong to the class itself.
It is executed before the Main() method.
A static constructor is called automatically by the runtime when the class is initialized. This means that it is called only once, when the class is first loaded into memory.
A static constructor can initialize static fields with default values or perform any necessary setup or initialization of static fields.
We would use a static constructor when we need to initialize static fields with default values.
namespace Program
{
internal class StaticConstructor
{
//Static Constructor
static StaticConstructor()
{
Console.WriteLine("Static constructor called");
}
static void Main(string[] args)
{
Console.WriteLine("Main method is called");
}
}
}