Working with Constructors in C# - Type of constructors and their properties

In our everyday programming we must have came across Constructors, In this article we will see some basics of Constructors, type of constructors, and their properties.

If you are a beginner, then this article will help you clear all your doubts about constructors and their usage.

What is a Constructor?


A Constructor is a special method, whose name is same as the class name and do not have any return type. Constructors are usually used to initialize the data members of the class.

Key Points about Constructors;
  • Constructors have the same name as the class.
  • Constructors are used to initialize the data members of the class
  • Constructors do not have any return type not even void.
  • Constructors can not be called explicitly by user.
  • If you want some code to get executed automatically then you can write those inside the constructors.



Example of a Constructor


Below is a simple example of a constructor that is used to initialize some data members of a class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Constructors
{
    class Program
    {
        static void Main(string[] args)
        {
            //Implementing the constructor and passing values to it.
            Employee objEmployee = new Employee("015-0012", "Tapan kumar");

            Console.WriteLine("EmpID: " + objEmployee.EmpID);
            Console.WriteLine("FullName: " + objEmployee.FullName);

            Console.ReadKey();
        }
    }

    public class Employee
    {
        public string EmpID { get; set; }
        public string FullName { get; set; }

        /// <summary>
        /// The is a constructor to initialize the member variables EmpID and FullName
        /// </summary>
        /// <param name="empId"></param>
        /// <param name="fullName"></param>
        public Employee(string empId, string fullName)
        {
            EmpID = empId;
            FullName = fullName;
        }
    }
}
So, in the above example we have a class named Employee, which has two data members EmpID and FullName.

As you can see I have defined a Constructor whose name is same as the Class name, Employee. It takes two parameters and then inside it initializes the data members.

If you have marked then you will find the Constructor did not have any return type. And we have to parse the parameters in the time of initialization of the object of the class.

Below is the output of this program.


Type of Constructors


There are four type of constructors as listed below.
  • Default Constructors
  • Parameterized Constructors
  • Static Constructors
  • Private Constructors
  • Copy Constructors
Let's explore these constructors one by one.

Default Constructor


Default Constructor is a constructor which does not take any parameters. By default C# creates a default constructor and whenever an object of the class is created, it instantiates the data members.

Basically it initializes all integer values to 0 and string values to null.

Here is an example of a default constructor.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Constructors
{
    class Program
    {
        static void Main(string[] args)
        {
            //Implementing the constructor and passing values to it.
            Employee objEmployee = new Employee();

            Console.WriteLine("EmpID: " + objEmployee.EmpID);
            Console.WriteLine("FullName: " + objEmployee.FullName);

            Console.ReadKey();
        }
    }

    public class Employee
    {
        public string EmpID { get; set; }
        public string FullName { get; set; }

        /// <summary>
        /// The is a constructor to initialize the member variables EmpID and FullName
        /// </summary>
        /// <param name="empId"></param>
        /// <param name="fullName"></param>
        public Employee()
        {
            EmpID = "015-100";
            FullName = "Tapan kumar";
        }
    }
}
The above code gives the output as below;

OutPut: 
EmpID: 015-100
FullName: Tapan kumar


Parameterized Constructors


These are the constructors those take at least one parameter to initialize the data members. The advantage of parameterized constructor is that each instance of the class can be initialized to different values.

Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Constructors
{
    class Program
    {
        static void Main(string[] args)
        {
            //Implementing the constructor and passing values to it.
            Employee objEmployee = new Employee("015-0012", "Tapan kumar");

            Console.WriteLine("EmpID: " + objEmployee.EmpID);
            Console.WriteLine("FullName: " + objEmployee.FullName);

            Console.ReadKey();
        }
    }

    public class Employee
    {
        public string EmpID { get; set; }
        public string FullName { get; set; }

        /// <summary>
        /// The is a constructor to initialize the member variables EmpID and FullName
        /// </summary>
        /// <param name="empId"></param>
        /// <param name="fullName"></param>
        public Employee(string empId, string fullName)
        {
            EmpID = empId;
            FullName = fullName;
        }
    }
}
Here you can see that, during the object creation we are passing some parameters to the The above code gives the output as below;

OutPut:
EmpID: 015-100
FullName: Tapan kumar


Note: In case of parameterized constructors if you do not declare a default constructor then in each place while creating an object of the class, you have to pass the parameters.

 Static Constructor


The static constructor is the special type that does not take access modifiers or have parameters. It is called automatically to initialize the class before the first instance is created or any static members are referenced. The static constructor is not called directly. Users can't control the execution of the static constructor.

Example:
using System;

namespace Constructors
{
    class Program
    {
        static void Main(string[] args)
        {
            //Implementing the constructor and passing values to it.
            Employee objEmployee = new Employee("015-0012", "Tapan kumar");

            Employee.ShowEmpDetails();

            Console.ReadKey();
        }
    }

    public class Employee
    {
        public static string EmpID { get; set; }
        public static string FullName { get; set; }

        /// <summary>
        /// The is a constructor to initialize the member variables EmpID and FullName
        /// </summary>
        /// <param name="empId"></param>
        /// <param name="fullName"></param>
        public Employee(string empId, string fullName)
        {
            EmpID = empId;
            FullName = fullName;
        }

        public static void ShowEmpDetails()
        {
         Console.WriteLine("EmpID: " + EmpID);
            Console.WriteLine("FullName: " + FullName);
        }
    }
}
Note: A Static Constructor do not take any access modifier. It can not be called directly by user code.
OutPut:
EmpID: 015-100
FullName: Tapan kumar

Private Constructors


As the name suggests Private Constructor must have a private access modifier before it. And we can neither create any object of the class nor can inherit the class. 

Private constructors are used in classes that contain only static members. We can have the set of public constructors along with the private constructors in the class and the public constructors can access the private constructors from within the class through constructor chaining


Copy Constructors


Copy Constructor is one which takes an object of the same class as parameter. It is being used to copy variables from another object.

It is basically used to initialize the object with the same data values of another instance of the class.

Example:
using System;

namespace Constructors
{
    class Program
    {
        static void Main(string[] args)
        {
            //Implementing the constructor and passing values to it.
            Employee objEmployee = new Employee("015-0012", "Tapan kumar");

            Employee objEmployeeCopy = new Employee(objEmployee);

            Console.WriteLine("EmpID: " + objEmployeeCopy.EmpID);
            Console.WriteLine("FullName: " + objEmployeeCopy.FullName);

            Console.ReadKey();
        }
    }

    public class Employee
    {
        public  string EmpID { get; set; }
        public  string FullName { get; set; }

        /// <summary>
        /// The is a constructor to initialize the member variables EmpID and FullName
        /// </summary>
        /// <param name="empId"></param>
        /// <param name="fullName"></param>
        public Employee(string empId, string fullName)
        {
            EmpID = empId;
            FullName = fullName;
        }

        public Employee(Employee objEmployee)
        {
            EmpID = objEmployee.EmpID;
            FullName = objEmployee.FullName;
        }

    }
}
OutPut:
EmpID: 015-100
FullName: Tapan kumar

In the above code you can see we are passing the Employee object into the copy constructor which retains the values of the data members as in the objEmployee.

Now I guess you have a clear overview on Constructors and its types and how and where to use these constructors.

If you got any questions then please let me know by putting your valuable comments below.

Happy Codding...


No comments:

Post a Comment