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:
- When you use this keyword to call a constructor, the constructor should belong to the same class.
- You can also pass parameter in this keyword.
- This keyword always pointing to the members of the same class in which it is used.
- When you use this keyword, it tells the compiler to invoke the default constructor. Or in other words, it means a constructor that does not contain arguments.
Syntax:
class X
{
public X: this()
{
// Code..
}
}
- this keyword contains the same type and the same number of parameters that are present in the calling constructor.
Syntax:
class X
{
public X(int x): this(int)
{
// Code..
}
}
- This concept removes the assignment of replication of properties in the same class.
Below programs illustrate how to call the overloaded constructor using this keyword:
Example 1:
CSharp
using System;
class Geek {
public Geek()
{
Console.WriteLine( "Hello! Constructor 1" );
}
public Geek( int a)
: this ()
{
Console.WriteLine( "Hello! Constructor 2" );
}
}
public class GFG {
static public void Main()
{
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:
CSharp
using System;
class Geek {
public Geek( int a, double b, string c)
{
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
}
public Geek( int a, int b)
: this (50, 2.9, "Hello" )
{
Console.WriteLine(a);
Console.WriteLine(b);
}
}
public class GFG {
static public void Main()
{
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.