C#.NET method hiding vs overloading — predict the output. namespace CuriousTabConsoleApplication { class Baseclass { public void fun() { Console.WriteLine("Hi" + " "); } public void fun(int i) { Console.Write("Hello" + " "); } } class Derived : Baseclass { public void fun() { Console.Write("Bye" + " "); } } class MyProgram { static void Main(string[] args) { Derived d = new Derived(); d.fun(); d.fun(77); } } } What will be printed?
-
AHi Hello Bye
-
BBye Hello
-
CHi Bye Hello
-
DError in the program
-
ENone of these
Answer
Correct Answer: Bye Hello
Explanation
Introduction / Context:This question examines two different concepts: method hiding (same signature in derived without override) and method overloading (same name, different parameters). It asks you to trace which implementation is invoked for each call.
Given Data / Assumptions:
Baseclassdefinesfun()andfun(int).Deriveddefines its ownfun()(hides base version; nooverridesince base is notvirtual).- Calls are invoked through a
Derivedvariable.
Concept / Approach:Overloading is resolved by signature at compile time. Hiding replaces the method in the derived class with the same signature when called via a derived-type reference. Since fun(int) is defined only in the base, the call with an int argument binds to the base implementation.
Step-by-Step Solution:
Calld.fun() → Derived.fun() chosen → prints “Bye ”.Call d.fun(77) → only Baseclass.fun(int) matches → prints “Hello ”.Combined output: Bye Hello (spacing as per writes).Verification / Alternative check:Mark Baseclass.fun() as virtual and Derived.fun() as override; behavior for fun() via a base reference becomes polymorphic but here the reference is Derived so you still see the derived implementation.
Why Other Options Are Wrong:(a) lists three items and the order is incorrect; (c) includes “Hi” which is not called in this flow; (d) code compiles fine.
Common Pitfalls:Confusing hiding with overriding and assuming that defining a new method in derived automatically overrides the base implementation without virtual/override.
Final Answer:Bye Hello