Accessing hidden and base fields: which line should be added so that fun() prints 9 13 for the following code? class BaseClass { protected int i = 13; } class Derived : BaseClass { int i = 9; public void fun() { // [*** Add statement here ***] } }

Difficulty: Easy

Correct Answer: Console.WriteLine(i + " " + base.i);

Explanation:


Introduction / Context:
When a derived class declares a field with the same name as a base class field, the derived field hides the base field. C# allows accessing the hidden base member using the base qualifier.



Given Data / Assumptions:

  • BaseClass.i is protected and equals 13.
  • Derived introduces its own int i = 9.
  • We need to print “9 13”.


Concept / Approach:
Inside Derived, the unqualified identifier i resolves to the derived field (value 9). To reach the base field, write base.i (value 13). Printing “i then base.i” yields “9 13”.



Step-by-Step Solution:

Use the hidden derived field via i.Use the base-class field via base.i.Compose the output: Console.WriteLine(i + " " + base.i);


Verification / Alternative check:
Swap order to base.i first and you would get “13 9”, which does not match the requirement.



Why Other Options Are Wrong:
Options using mybase do not exist in C#. Using this.i prints the derived field twice (“9 9”). Printing base.i first gives wrong order.



Common Pitfalls:
Assuming this accesses the base field automatically; forgetting that base is needed to access the hidden base member.



Final Answer:
Console.WriteLine(i + " " + base.i);

More Questions from Inheritance

Discussion & Comments

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