Hiding vs overriding — what does the derived method do in this code? public class Sample { public int x; public virtual void fun() { } } public class DerivedSample : Sample { new public void fun() { } }

Difficulty: Medium

Correct Answer: DerivedSample hides the fun() method of the base class.

Explanation:


Introduction / Context:
In C#, new hides a base member; override replaces it polymorphically. This question distinguishes hiding from overriding.



Given Data / Assumptions:

  • Base fun() is virtual.
  • Derived fun() uses new, not override.


Concept / Approach:
Using new creates a new member that hides the base member when the variable is typed as DerivedSample. Calls through a Sample reference still bind to the base virtual unless the derived used override.



Step-by-Step Solution:

1) Hide: new public void fun() — compile-time hiding.2) Override would be: public override void fun() — runtime polymorphism.


Why Other Options Are Wrong:

  • B: Through a Sample reference, the base virtual dispatch targets the base unless override is used.
  • C: Hiding does not replace for all calls.
  • D: You can hide without new; the compiler warns but still hides.


Common Pitfalls:
Assuming new implies override-like behavior.



Final Answer:
DerivedSample hides the fun() method of the base class.

Discussion & Comments

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