Constructor Chaining in C#

In this post, we will look at constructor chaining in C#.

What is Constructor Chaining?

Constructor chaining occurs when you use one constructor in a class to call another constructor on the same class. Often, because the constructors must have different signatures, you supply a safe or default value for the second constructor.

Listing 1.1 – Constructor Chaining

public MessagePrinter(string message) : this(message, 1)
{
            
}

public MessagePrinter(string message, int counter)
{
    for(int i = 0; i < counter; i++)
    {
        Console.WriteLine($"{i} - {message}");
    }
}

This will allow the default constructor to then call the second with a default argument specified for the counter value. However, I have a question for you. Which constructor executes first? If you said the default constructor, you would be wrong.

Listing 1.2 – Constructor Chaining Execution Order

public MessagePrinter(string message) : this(message, 1)
{
    Console.WriteLine("Constructor 1");
}

public MessagePrinter(string message, int counter)
{
    Console.WriteLine("Constrctor 2");

    for(int i = 0; i < counter; i++)
    {
        Console.WriteLine($"{i} - {message}");
    }
}

Figure 1.1 – Output from Listing 1.2

Constructor 2
0 - Test message
Constructor 1

Conclusion

Since the default constructor is called last, I have to wonder if there is any inherent value in constructor chaining at all. Any work that would be done in the default constructor is executed after the chained constructors so it may even be a bit dangerous. I know there are circumstances that demand a default constructor, however. Those scenarios are still valid but just be aware of the risks.

Leave a Reply

Your email address will not be published.