A Constructor is a special method of a Class, which is used to initialize the members of the same class. Whenever an Object of a class is created , a Constructor is called by default. Constructor do not return values and always have the same name as the Class.
As shown in above image , I have created a Employee class and it has three properties that is EmployeeId, Name and Department. I have created a Constructor with same name as class that is Employee and it has a public specifier. Constructor name always be same as class name and it is used for initialization of members in any class. We have initialize EmployeeId with 1 , Name with "John Saffer" and Department with "IT". Below is the code example for constructor so that you can easily understand to it.
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }=String.Empty;
public string Department { get; set; }=String.Empty;
public Employee()
{
EmployeeId = 1;
Name = "John Saffer";
Department = "IT";
}
}
There are 5 Types of Constructors are available in C# , below is the list of Constructors in C#.
Default constructor is a parameterless constructor and invoked every time when an object is created for class. Default constructor always set some default values to members as like 0 for int members and null for string and objects. Below is the image for explaining the default constructor.
As you can see in above image Employee is the default constructor there is no initialization for EmployeeId, Name and Department when we create an object it will automatically set 0 for default values.
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public Employee()
{
Console.WriteLine("Called a default constructor and set 0 for int and null for strings");
}
}
As you can see in below image we have created a object for Employee class in program.cs file and write the values of EmployeeId and Name into the console.
Employee emp = new Employee();
Console.WriteLine(emp.EmployeeId);
Console.WriteLine(emp.Name);
Parameterized constructor is a constructor with minimum one parameter and set a different value for parameter every time when an object is created for class. Parameterized constructor always set values that is provided in object creation for parameter list. Below is the image for explaining the Parameterized constructor.
As you can see in above image Employee is the Parameterized constructor with two parameters one is type int and other is type string. empid is the int parameter and name is the string parameter and we have initialised these parameter inside the constructor as you can see in the above image and while creating the object we need to pass these parameter values..
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public Employee(int empid,string name)
{
this.EmployeeId = empid;
this.Name = name;
}
}
As you can see in below image we have created a object for Employee class in program.cs file and pass the values for empid and name during the object creation so that while creating the constructor these will initialize into the constructor .
Employee emp = new Employee(25,"James cotlin");
Console.WriteLine("First Parameter is " + emp.EmployeeId);
Console.WriteLine("Second Parameter is " + emp.Name);
As the name suggest it has a copy feature means Copy constructor is a constructor used for creating an object by copying the variables from other objects . It is mainly used for initializing new values to variables from existing variables.
As you can see in above image Employee is the Parameterized constructor with three parameters one is type int and other is type string and
third is also type string. empid is the int parameter and name and department is the string parameter and we have initialised these parameter inside the constructor as you can see
in the above image and while creating the object we need to pass these parameter values..
As our concern is copy construtor so we have created other constructor and passed a object of Employee class as a parameter into it
and initializes the new variables with existing variables by emp object in below code example.
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public Employee(Employee emp)
{
EmployeeId = emp.EmployeeId;
Name = emp.Name;
Department = emp.Department;
}
public Employee(int employeeId, string name, string department)
{
EmployeeId = employeeId;
Name = name;
Department = department;
}
}
As you can see in below image we have created one object for Employee class in program.cs file and pass the values for empid , name and department in construtor then we have created a second object of employee class and we have passed first object into the constructor then it will copy the values from object one that emp1 to object 2 that is emp2 using the constructor invocation.
Employee emp1 = new Employee(25,"William Tell","CS");
Employee emp2 = new Employee(emp1);
Console.WriteLine("First Parameter Copied from first object emp1 is " + emp2.EmployeeId);
Console.WriteLine("Second Parameter Copied from first object emp1 is " + emp2.Name);
Console.WriteLine("Third Parameter Copied from first object emp1 is " + emp2.Department);
Private constructor is created by using the private specifier with constructor. We can not create an instance of a class having the private constructor and no any other class will inherit the class directly in which private constructor is defined.
As you can see in above image we have created a private constructor of Employee class and one static property EmployeeId of type int. We also created a method named EmployeesCount() to count the EmployeeId for testing the constructor workflow.
public class Employee
{
public static int EmployeeId { get; set; }
private Employee()
{
}
public static int EmployeesCount()
{
return EmployeeId++;
}
}
If you tried to create an object of Class having the private constructor it will generate an error as shown in Above image.
As you can see in above image we have tried to create an object for Employee class in program.cs file but we got an error so that we commented the first line to creating the object of Employee class. To access the members of class we have to declared them static then we can access them directly we class name as like in above image we have access EmployeeId with class name Employee and set the values for it and then we also call the EmployeesCount() method for incrementing the EmployeeId count. You can also find the same code in below code example.
//Employee emp1 = new Employee(); It will generate an error when creating an object
Employee.EmployeeId = 1000;
Employee.EmployeesCount();
Console.WriteLine("Employee Count is "+ Employee.EmployeeId);
Employee.EmployeesCount();
Console.WriteLine("Employee Count is " + Employee.EmployeeId);
When we tried to inherit the Employee class that has a private constructor with ChildClassA then compiler throws an error for it so that we can not inherit the class which contains the private constructor in it. Below is the image attached in which you can see the error thrown by compiler when inheriting a class contains the private constructor.
Static constructor is created by using the Static specifier with constructor. We can create a Static constructor in Static Class as
well as non Static Class Also. Static Constructor invoked only once no matter how many objects are created. If you have created more
than one object then only first object reference will invoked the Static constructor.
Static Constructor always invoked before the instance constructors.
As you can see in above image we have created a static constructor of Employee class and one Instance Constructor. We also created a method named PrintFullName() to call when object of Employee class is created.
public class Employee
{
static Employee()
{
Console.WriteLine("This is Static Constructor of Employee Class");
}
public Employee()
{
Console.WriteLine("This is Instance Constructor of Employee Class");
}
public void PrintFullName()
{
Console.WriteLine("Employee Full Name is Ricky Martin");
}
}
We can not use modifiers with static constructor as shown in below image when we use the modifier it will generate an error.
Now we have created the three objects of Employee classs and called the PrintFullName() method with all the three objects as shown in below image.
//Employee emp1 = new Employee(); It will generate an error when creating an object
Employee.EmployeeId = 1000;
Employee.EmployeesCount();
Console.WriteLine("Employee Count is "+ Employee.EmployeeId);
Employee.EmployeesCount();
Console.WriteLine("Employee Count is " + Employee.EmployeeId);
As you can see in above image and code we have created 3 object for Employee class in program.cs file and with each object we call the instance method . Static constructor will invoked only once and instance constructor will be invoked every time means it will invoke for 3 times and Static constructor will be called before all the constructors as shown in below output window.
A Derived Class can not inherit the Constructor of its Base Class. All the Derived Classes have their own default Constructor.
When you intiantiate a Derived Class , first the Constructor of Base Class is called and then derived class Constructor is called.
The Constructor of Base Class is initializes the members of the Base Class before derived class constructor is executed.
As Shown in above images I have created a Base Class Employee and inside the Employee Class , Created a Static Constructor and a instance constructor and a void method also I have created a ChildClassA and inherits it from Employee Class and inside the Child class I have created a Static and a instance Constructor and then called it from program.cs file as shown in above images. Static constructor always called before the instance constructor and then base class constructor called then child class constructors.
A Destructor or finalizer is called when the Object is finally destroyed and the garbage is collected.
Points to Remember :-
About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the
applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server,
EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.