Bird
0
0

What will be printed when the following C# code runs?

medium📝 Predict Output Q4 of 15
C Sharp (C#) - Inheritance
What will be printed when the following C# code runs?
class Alpha {
  public Alpha() : this(20) {
    Console.WriteLine("No-arg constructor");
  }
  public Alpha(int n) {
    Console.WriteLine($"Int constructor: {n}");
  }
}

class Program {
  static void Main() {
    new Alpha();
  }
}
ANo-arg constructor Int constructor: 20
BInt constructor: 20 No-arg constructor
CNo-arg constructor
DInt constructor: 20
Step-by-Step Solution
Solution:
  1. Step 1: Understand constructor chaining order

    The constructor with no arguments calls the one with an int parameter first.
  2. Step 2: Execution flow

    The int constructor prints first: "Int constructor: 20". Then control returns to the no-arg constructor which prints "No-arg constructor".
  3. Final Answer:

    Int constructor: 20 No-arg constructor -> Option B
  4. Quick Check:

    Chained constructor runs before calling constructor [OK]
Quick Trick: Chained constructor executes before the calling one [OK]
Common Mistakes:
MISTAKES
  • Assuming calling constructor runs first
  • Expecting only one constructor to print
  • Ignoring chaining order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes