![]() |
VOOZH | about |
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:
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:
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.