Open In App

Invoking an overloaded constructor using this keyword in C#

Prerequisite : Constructors in C#
C# provides a powerful keyword known as this keyword and this keyword has many usages. Here we use this keyword to call an overloaded constructor from another constructor.
Important Points:
 

class X 
{

   public X: this()
   {

      // Code..

   }
}
class X
{
   public X(int x): this(int)
   {

       // Code..
   }
}

Below programs illustrate how to call the overloaded constructor using this keyword:
Example 1:
 






// C# program to illustrate how to invoke
// overloaded constructor using this keyword
using System;
class Geek {
 
    // Constructor without parameter
    public Geek()
    {
        Console.WriteLine("Hello! Constructor 1");
    }
 
    // Constructor with parameter
    // Here this keyword is used
    // to call Geek constructor
    public Geek(int a)
    : this()
    {
        Console.WriteLine("Hello! Constructor 2");
    }
}
 
// Driver Class
public class GFG {
 
    // Main method
    static public void Main()
    {
 
        // Create object of Geek class
        Geek obj = new Geek(2);
    }
}

Output: 
 

Hello! Constructor 1
Hello! Constructor 2

Explanation: In the above example, Geek class contains two constructors, i.e, Geek() is without parameter and Geek(int a) is with parameter. Now we call Geek() constructor in Geek(int a) by using this() keyword. Here this() keyword does not contain any argument because the constructor does not contain any parameter. 
Example 2:
 






// C# program to illustrate how to invoke
// overloaded constructor using this keyword
using System;
class Geek {
 
    // Constructor with parameters
    public Geek(int a, double b, string c)
    {
        Console.WriteLine(a);
        Console.WriteLine(b);
        Console.WriteLine(c);
    }
 
    // Constructor with parameters
    // Here this keyword is used
    // to call Geek constructor
    public Geek(int a, int b)
        : this(50, 2.9, "Hello")
    {
        Console.WriteLine(a);
        Console.WriteLine(b);
    }
}
 
// Driver Class
public class GFG {
 
    // Main method
    static public void Main()
    {
 
        // Create object of Geek class
        Geek obj = new Geek(15, 30);
    }
}

Output: 
 

50
2.9
Hello
15
30

Explanation: In the above example, Geek class contains two constructors, i.e, Geek(int a, double b, string c) and Geek(int a, int b) and both are parameterized constructors. Now we call Geek(int a, double b, string c) constructor in Geek(int a, int b) by using this(50, 2.9, “Hello”) keyword. Here this(50, 2.9, “Hello”) keyword contains the same number and type of argument that are present in the Geek(int a, double b, string c) constructor.
 


Article Tags :
C#