Constructors

Constructors are special methods that are required to create or “construct” objects. They allow you to assign the initial values for each data member of an array and add codes that you want to execute when you create an object. If you don’t include any constructors in a class, then the compiler will use a default constructor which is a constructor that has no parameters. You can have as many constructors as you want provided that they have a different set of parameters. Let’s take a look at a class that contains a constructor.

using System;
 
namespace ConstructorsDemo
{
    public class Person
    {
        public string name;
        public int age;
        public double height;
 
        //Explicitly declare a default constructor            
        public Person()                          
        {                                        
        }                                        
 
        //Constructor that has 3 parameters                   
        public Person(string n, int a, double h) 
        {                                        
            name = n;                            
            age = a;                             
            height = h;                          
        }                                        
 
        public void ShowInformation()
        {
            Console.WriteLine("Name: {0}", name);
            Console.WriteLine("Age: {0} years old", age);
            Console.WriteLine("Height: {0}cm", height);
        }
    }
 
    public class Program
    {
        public static void Main()
        {
            Person firstPerson = new Person();                 
            Person secondPerson = new Person("Mike", 23, 158); 
 
            firstPerson.name = "Jack";
            firstPerson.age = 21;
            firstPerson.height = 160;
            firstPerson.ShowInformation();
 
            Console.WriteLine(); //Seperator                  
 
            secondPerson.ShowInformation();
        }
    }
}

Example 1 – A Class with a Constructor

Name: Jack
Age: 21 years old
Height: 160cm

Name: Mike
Age: 23 years old
Height: 158cm

The program in Example 1 is the same program that we saw in the last lesson. We added two constructors for class Person. One is the default constructor  (lines 12-14) and the other is a constructor that accepts three arguments  (lines 17-22).You notice that a constructor is just like a method, but it must not have a return type, not even void. The name of a constructor must exactly match with the name of the  class. The default constructor has nothing inside its body. This is the same as the default constructor being called if we did not provide any constructors for a class. We will see later how we can assign default values to data members when using a default constructor. Take a look at the second constructor. It has the same name as the first one. Constructors can be overloaded like  methods. Let’s look at how we can call a specific constructor based on the declaration of the instances of the class.

Person firstPerson = new Person();
Person secondPerson = new Person("Mike", 23, 158);

On the first instance of person, we used the default constructor because there are no arguments inside the parentheses. On the second declaration, we are now using the second constructor because the three arguments that the parameter of the constructor is expecting are provided. The code below shows the effect of using two different constructors.

firstPerson.name = "Jack";
firstPerson.age = 21;
firstPerson.height = 160;
firstPerson.ShowInformation();

Console.WriteLine(); //Seperator

secondPerson.ShowInformation();

As you can see, the object that used the default constructor requires you to assign the values for it data members so it can show something if you call the ShowInformation() method. Contrast to the second object that used the parameterized constructor, you just call the method and everything will run as expected. This is because, you already gave the values for the data members when you declared the instance so there’s no need to reassign values unless you want to modify the value of a data member.

Providing Default Values for the Default Constructor


The program in Example 1 showed a default constructor that has an empty body. You can add codes inside the default constructor. You can assign default values to the data members if nothing is provided by the user.

public Person()
{
   name = "No Name";
   age = 0;
   height = 0;
}

Now our default constructor has something to do. If we declared an instance that uses this constructor, then it will be assigned the default values.

Person person1 = new Person();
person1.ShowInformation();
Name: No Name
Age: 0 years old
Height: 0cm

Using the this Keyword


Another way of providing default values is by using the this keyword. The example below shows a modified program in Figure1 and uses 4 constructors  with different number of parameters.

using System;
 
namespace ConstructorDemo2
{
    public class Person
    {
        public string name;
        public int age;
        public double height;
 
        public Person()                   
            : this("No Name", 0, 0)       
        {
        }
 
        public Person(string n)           
            : this(n, 0, 0)               
        {
        }
 
        public Person(string n, int a)    
            : this(n, a, 0)               
        {
        }
 
        public Person(string n, int a, double h)
        {
            name = n;
            age = a;
            height = h;
        }
 
        public void ShowInformation()
        {
            Console.WriteLine("Name: {0}", name);
            Console.WriteLine("Age: {0} years old", age);
            Console.WriteLine("Height: {0}cm\n", height);
        }
    }
 
    public class Program
    {
        public static void Main()
        {
            Person firstPerson = new Person();                 
            Person secondPerson = new Person("Jack");          
            Person thirdPerson = new Person("Mike", 23);       
            Person fourthPerson = new Person("Chris", 18, 152);
 
            firstPerson.ShowInformation();
            secondPerson.ShowInformation();
            thirdPerson.ShowInformation();
            fourthPerson.ShowInformation();
        }
    }
}

  Example 2 – Using the this Keyword

Name: No Name
Age: 0 years old
Height: 0cm
Name: Jack
Age: 0 years old
Height: 0cm

Name: Mike
Age: 23 years old
Height: 0cm

Name: Chris
Age: 18 years old
Height: 152cm

We declared four constructors for our modified class. You can have as many constructors in a class when deemed necessary. The first constructor is the default parameterless constructor. The second constructor is the one that has one parameter. The third constructor has two parameters, and the fourth constructor has three parameters. Take note of the fourth constructor  in lines 26-31. The other three constructors will rely on the constructor.

Lines 11-14 is the default parameterless constructor. Notice the use of the this keyword after placing a colon (:) . The  this keyword lets you call another existing  constructor inside the class. We give the default values for the data members.  Since we provided three arguments inside the parentheses following the this keyword, the constructor with three parameters was called and three arguments  was passed to its parameters. The code inside the body of the fourth constructor is executed which assigns the values of the parameters to their respective data members. We didn’t write any code inside the body of the first constructor since that will be handled by the fourth constructor. If we write codes inside the body of the default constructor, then the fourth constructor will be executed before the code inside the default constructor.

The second constructor (lines 16-19) requires one argument which is the name of the person.  When this parameter is filled up with a string value, that value is then passed to the  parameters of the fourth constructor along with the other two default values (0 for age and 0 for height). Again, we didn’t write any code inside the body of the second constructor because it will be handled by the fourth parameter.

Lines 21-24 is the third constructor which is similar to the second constructor but has two parameters. The value of the two parameters  of the third constructor along with a default value of 0 for the third argument is passed to the fourth constructor  using the thiskeyword.

Person firstPerson = new Person();
Person secondPerson = new Person("Jack");
Person thirdPerson = new Person("Mike", 23);
Person fourthPerson = new Person("Chris", 18, 152);

With multiple constructors for our class, we have multiple ways of creating  our class depending on which data are needed. We declared four instances of the Person class and we used the four different variations of its constructor. We then displayed the values of the data members of each instance.

There’s another use for the this keyword. What if the parameter name for your class method or constructor is similar the name of the one of the data members.

public Person(string name, int age, double height)
{
   name = name;
   age = age;
   height = height;
}

This will give ambiguity to the code and the compiler cannot determine which variable you are assigning to and which variable is being assigned a value. This is where the this keyword is used.

public Person(string name, int age, double height)
{
   this.name = name;
   this.age = age;
   this.height = height;
}

We precede each of the data members with the this keyword to indicate that what’s being assigned a value are the attributes of “this” class. The this keyword represents the reference of the  object itself.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *