Method hiding with new: what is printed? namespace CuriousTabConsoleApplication { class Baseclass { public void fun() { Console.Write("Base class "); } } class Derived1 : Baseclass { new void fun() { Console.Write("Derived1 class "); } } class Derived2 : Derived1 { new void fun() { Console.Write("Derived2 class "); } } class Program { static void Main(string[] args) { Derived2 d = new Derived2(); d.fun(); } } }

Difficulty: Easy

Correct Answer: Derived2 class

Explanation:


Introduction / Context:
This problem illustrates method hiding using the new modifier in C#. Unlike virtual/override dispatch, new creates a new member that hides the inherited one when the compile-time type matches the derived class.



Given Data / Assumptions:

  • Baseclass.fun, Derived1.fun, and Derived2.fun are all non-virtual and hidden with new.
  • d is declared as Derived2 and instantiated as Derived2.


Concept / Approach:
For non-virtual methods, the invoked method is selected based on the compile-time type of the reference. Because d has compile-time type Derived2, calling d.fun() invokes Derived2.fun(), printing “Derived2 class”. No base methods are called.



Step-by-Step Solution:

Determine compile-time type of d → Derived2.fun() in Derived2 hides fun() in Derived1 and Baseclass.Call d.fun() → Derived2.fun() executes → prints “Derived2 class”.


Verification / Alternative check:
Cast the reference to base types to observe different outputs: ((Derived1)d).fun() prints “Derived1 class” and ((Baseclass)d).fun() prints “Base class”.



Why Other Options Are Wrong:
They assume virtual dispatch or concatenated prints which do not occur without calling base methods explicitly.



Common Pitfalls:
Confusing new (hiding) with override (polymorphic override via virtual).



Final Answer:
Derived2 class

More Questions from Inheritance

Discussion & Comments

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