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.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp Class

  • Call Constructor of Base Class From the Constructor of Child Class in C#