C 🧠 Constructor Chaining and Inheritance in C#: What Gets Printed and Why?

🧠 Constructor Chaining and Inheritance in C#: What Gets Printed and Why?

Constructors are often overlooked when we talk about object-oriented programming, but understanding how they interact — especially across base and derived classes — is critical. Here's a short but powerful challenge that explores constructor chaining and inheritance in C#.

Let’s analyze this snippet and predict the output.


🔍 The Challenge

private class Program
{
	public static void Main()
	{
		ClassA refA = new ClassA();
		ClassB refB = new ClassB();
	}
}

class ClassA
{
    public ClassA() : this(10)
    {
        Console.WriteLine("apple");
    }

    public ClassA(int pValue)
    {
        Console.WriteLine("banana");
    }
}

class ClassB : ClassA 
{
    public ClassB() : base(0) 
    {
        Console.WriteLine("tomato");
    }
}

🧠 Step-by-Step Execution

 

1️⃣ First Line:

ClassA refA = new ClassA();
  • This calls the parameterless constructor of ClassA:

public ClassA() : this(10)
  • Which means it first calls the constructor with int parameter:

public ClassA(int pValue) { Console.WriteLine("banana"); }
  • Then, after that finishes, the parameterless constructor prints:

Console.WriteLine("apple");

✅ So this line produces:

banana
apple 

2️⃣ Second Line:

ClassB refB = new ClassB();
  • ClassB is a derived class that explicitly calls:

    public ClassB() : base(0)
  • Which invokes the same ClassA(int) constructor that prints:

    banana
  • Then the body of ClassB's constructor runs:

    Console.WriteLine("tomato");

✅ So this line produces: 

       banana
       tomato


✅ Final Output:

banana
apple
banana
tomato

 🎯 What’s the Lesson?

This challenge beautifully illustrates how constructor calls cascade across class hierarchies and within the same class using this(...) and base(...).

💡 Key Takeaways

  1. this(...) calls another constructor in the same class

    • The called constructor runs before the current one’s body.

  2. base(...) calls a constructor in the parent class

    • That constructor is always executed before the derived constructor.

  3. Constructor execution order flows from base to derived

    • Even if the derived class is the one being instantiated.

  4. Parameterless constructors aren't used if an explicit base constructor is called

    • You must match signatures exactly when using base(...).


🧠 Real-World Tip

Constructor chaining is essential when building:

  • Reusable frameworks

  • Dependency-injected services

  • Deep inheritance hierarchies

  • Clean APIs with multiple constructor overloads

Understanding this flow helps prevent bugs and ensures consistent object initialization.


Have you ever hit a bug because of unexpected constructor behavior? Or used chaining to simplify class construction?

💬 Share your story in the comments

Add comment