Bird
0
0

Given the interface and classes below, how would you write a method PerformWork that accepts any IWorker and calls its Work() method?

hard🚀 Application Q9 of 15
C Sharp (C#) - Interfaces

Given the interface and classes below, how would you write a method PerformWork that accepts any IWorker and calls its Work() method?

interface IWorker { void Work(); }
class Employee : IWorker {
  public void Work() { Console.WriteLine("Employee working"); }
}
class Robot : IWorker {
  public void Work() { Console.WriteLine("Robot working"); }
}
Avoid PerformWork(IWorker worker) { worker.Work(); }
Bvoid PerformWork(Employee worker) { worker.Work(); }
Cvoid PerformWork(Robot worker) { worker.Work(); }
Dvoid PerformWork(object worker) { worker.Work(); }
Step-by-Step Solution
Solution:
  1. Step 1: Use interface type as parameter

    Method should accept IWorker to handle any implementing class.
  2. Step 2: Call Work() method on interface reference

    Calling worker.Work() invokes the correct implementation.
  3. Final Answer:

    void PerformWork(IWorker worker) { worker.Work(); } -> Option A
  4. Quick Check:

    Use interface type for polymorphic behavior. [OK]
Quick Trick: Use interface type to accept all implementations [OK]
Common Mistakes:
MISTAKES
  • Restricting parameter to concrete classes
  • Using object type without casting
  • Not calling Work() method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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