C#.NET constructor chaining — predict the output. namespace CuriousTabConsoleApplication { class Baseclass { int i; public Baseclass(int ii) { i = ii; Console.Write("Base "); } } class Derived : Baseclass { public Derived(int ii) : base(ii) { Console.Write("Derived "); } } class MyProgram { static void Main(string[] args) { Derived d = new Derived(10); } } } What will be printed?

Difficulty: Easy

Correct Answer: Base Derived

Explanation:

Introduction / Context:This tests your understanding of base-constructor invocation using the base keyword and the order in which constructors are executed in C#.

Given Data / Assumptions:

  • Baseclass exposes only a parameterized constructor.
  • Derived chains to it via : base(ii).
  • Console writes occur in each constructor.

Concept / Approach:When constructing a derived object, the runtime first calls the base constructor, then the derived constructor. The syntax : base(args) is the correct way to invoke a specific base constructor.

Step-by-Step Solution:

Create new Derived(10) → invokes Derived(int).Derived(int) specifies : base(ii) → calls Baseclass(int) first → prints "Base ".Control returns to Derived(int) body → prints "Derived ".Net output: Base Derived.

Verification / Alternative check:Remove : base(ii) and you will get a compile-time error because the base does not have a parameterless constructor.

Why Other Options Are Wrong:(a) Not necessary; parameterized chaining suffices. (b) Reverses order; incorrect. (c) Syntax is correct. (d) base.Baseclass(ii) is not C# syntax.

Common Pitfalls:Assuming derived constructors run before base, or thinking base requires type qualification.

Final Answer:Base Derived

More Questions from Inheritance

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion