Call Constructor From Another Constructor in C#

Muhammad Maisam Abbas Mar 16, 2021
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.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

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.

LinkedIn

Related Article - Csharp Class