Call Constructor From Another Constructor in C#

This tutorial will discuss methods to call one constructor from another constructor of the same class in C#.
Call One Constructor From Another Constructor of the Same Class With this
Keyword in C#
If our class has multiple constructors and we want to call one constructor from another constructor, we can use the this
keyword in C#. The this
keyword is a reference to the instance of the current class in C#. The following code example shows us how we can call one constructor of a class from another constructor of the same class with the this
keyword in C#.
using System;
namespace call_another_constructor
{
class sample
{
public sample()
{
Console.WriteLine("Constructor 1");
}
public sample(int x): this()
{
Console.WriteLine("Constructor 2, value: {0}",x);
}
public sample(int x, int y): this(x)
{
Console.WriteLine("Constructor 3, value1: {0} value2: {1}", x, y);
}
}
class Program
{
static void Main(string[] args)
{
sample s1 = new sample(12, 13);
}
}
}
Output:
Constructor 1
Constructor 2, value: 12
Constructor 3, value1: 12 value2: 13
We created the sample
class with 3 different constructors. The constructor sample(int x, int y)
calls the constructor sample(int x)
and passes x
as a parameter with this(x)
. The constructor sample(int x)
then calls the constructor sample()
with this()
. The sample()
constructor gets executed before the sample(int x)
constructor and the sample(int x)
constructor gets executed before the sample(int x, int y)
constructor.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedInRelated Article - Csharp Class
- Friend Class Equivalent in C#
- Extend a Class in C#
- Interface vs Abstract Classes in C#
- Include a Class Into Another Class in C#
- Nested Classes in C#
- Inherit From Multiple Classes in C#