In C#, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C# has the same name as class or struct.
There can be two types of constructors in C#.
A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.
Let’s see example of the default constructor .
using System; public class Employee { public Employee() { Console.WriteLine("Default Constructor Invoked"); } } class TestEmployee{ public static void Main(string[] args) { Employee e1 = new Employee(); Employee e2 = new Employee(); } }
Output:
Default Constructor Invoked Default Constructor Invoked
A constructor which has parameters is called parameterized constructor. It is used to provide different values to distinct objects.
Parameterized Constructor is used normally to intialise members of the object.
Below is an example of a Parameterized Constructor.
using System; public class Employee { public int id; public String name; public float salary; public Employee(int i, String n,float s) { id = i; name = n; salary = s; } public void display() { Console.WriteLine(id + " " + name+" "+salary); } } class TestEmployee{ public static void Main(string[] args) { Employee e1 = new Employee(101, "Sonoo", 890000f); Employee e2 = new Employee(102, "Mahesh", 490000f); e1.display(); e2.display(); } }
A destructor works opposite to constructor, It destructs the objects of classes. It can be defined only once in a class. Like constructors, it is invoked automatically.
A Destructor has no return type and has exactly the same name as the class name (Including the same case).
It is distinguished apart from a constructor because of the Tilde symbol (~) prefixed to its name.
Note: C# destructor cannot have parameters. Moreover, modifiers can’t be applied on destructors.
Let’s see an example of constructor and destructor in C# which is called automatically.
using System; public class Employee { public Employee() { Console.WriteLine("Constructor Invoked"); } ~Employee() { Console.WriteLine("Destructor Invoked"); } } class TestEmployee{ public static void Main(string[] args) { Employee e1 = new Employee(); Employee e2 = new Employee(); } }
Output:
Constructor Invoked Constructor Invoked Destructor Invoked Destructor Invoked
Try the following example in the editor below.
We have a class defined for Student. Create a constructor for the class which takes three parameters name(string), age(int), rollno(int) and assign values to the member variables. Also, create a destructor which prints name, age, rollno each in new line.