Define Constructors

A constructor is a member function of the class with the same name as its class. In other words, Constructor is the same as a method inside class with the same name as a class without return type. It gets called for every new object creation. Constructor mainly used for initializing member functions of the class.

using System;

namespace ConsoleApplication3

{

      class Program

                   {
                                  static void Main(string[] args)
                                  {
                                       Employee e = new Employee("John");
                                       Console.Write(e.GetEmployee());
                                  }
                   }
 
                   class Employee
                   {
                                  string EmployeeName;
                                  public Employee() //Default Constructor
                                  {
                                  }
                                  public Employee(string s) //Parameterized Constructor
                                  {
                                        EmployeeName = s;
                                  }
                                  public string GetEmployee()
                                  {
                                       return EmployeeName;
                                   }

     }

  }

 

             There are 3 different types of constructors:

·         Default Constructor: This constructor has no argument. If we create an object without passing any parameter it goes to the default constructor. If we did not declare this constructor in a class, it takes by default it. In the above example, there is one Default Constructor.

·         Parameterized constructor: This type of constructor has much argument. We can define multiple constructors with a different signature in the parameter (This Concept is called Method Overloading).

·         Copy constructor: A copy constructor is used to create a copy of the existing object as a new object. This constructor takes the reference of the object to be copied as an argument.

Post a Comment

0 Comments