Bird
0
0

What will be the output of this C# code?

medium📝 Predict Output Q13 of 15
C Sharp (C#) - Interfaces
What will be the output of this C# code?
interface IAnimal { void Speak(); }
class Dog : IAnimal { public void Speak() { Console.WriteLine("Woof"); } }
class Cat : IAnimal { public void Speak() { Console.WriteLine("Meow"); } }
static void Main() {
IAnimal animal = new Dog();
animal.Speak();
animal = new Cat();
animal.Speak();
}
AMeow Woof
BWoof Meow
CWoof Woof
DMeow Meow
Step-by-Step Solution
Solution:
  1. Step 1: Understand interface usage

    The variable animal is of type IAnimal and first assigned a Dog object, so calling Speak() prints "Woof".
  2. Step 2: Change object and call method again

    animal is then assigned a Cat object, so calling Speak() prints "Meow".
  3. Final Answer:

    Woof Meow -> Option B
  4. Quick Check:

    Interface variable calls method of assigned object [OK]
Quick Trick: Interface variable calls method of current object type [OK]
Common Mistakes:
MISTAKES
  • Assuming interface variable fixes method output
  • Mixing order of outputs
  • Forgetting to implement interface methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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