Bird
0
0

Find the error in this C# code:

medium📝 Debug Q6 of 15
C Sharp (C#) - Inheritance
Find the error in this C# code:
class Parent { public void Greet() { Console.WriteLine("Hello from Parent"); } } class Child : Parent { public void Greet() { Console.WriteLine("Hello from Child"); } } class Program { static void Main() { Parent p = new Child(); p.Greet(); } }
AError: Greet() must be virtual in Parent to override
BNo error, output is "Hello from Child"
CNo error, output is "Hello from Parent"
DError: Child cannot have method with same name
Step-by-Step Solution
Solution:
  1. Step 1: Check method hiding vs overriding

    Parent's Greet() is not virtual, so Child's Greet() hides it but does not override.
  2. Step 2: Analyze method call on Parent reference

    Calling p.Greet() calls Parent's method because method is not virtual, so output is "Hello from Parent".
  3. Final Answer:

    No error, output is "Hello from Parent" -> Option C
  4. Quick Check:

    Non-virtual method call = base method runs [OK]
Quick Trick: Non-virtual methods call base version even if object is derived [OK]
Common Mistakes:
MISTAKES
  • Expecting Child's method to run without virtual keyword
  • Thinking code causes compilation error
  • Confusing method hiding with overriding

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes