Bird
0
0

You want to write a method that accepts any object that can be saved to a database. Which approach best uses interfaces to achieve this?

hard🚀 Application Q15 of 15
C Sharp (C#) - Interfaces
You want to write a method that accepts any object that can be saved to a database. Which approach best uses interfaces to achieve this?
ADefine an interface ISaveable with method Save(), then accept ISaveable parameter
BUse object type parameter and check type inside method
CCreate a base class Saveable and inherit from it
DWrite separate methods for each class type
Step-by-Step Solution
Solution:
  1. Step 1: Understand interface benefits

    Interfaces allow different classes to share a common method signature, enabling polymorphism.
  2. Step 2: Analyze options for flexibility and maintainability

    Define an interface ISaveable with method Save(), then accept ISaveable parameter uses an interface ISaveable with Save() method, allowing any class implementing it to be passed in.
  3. Step 3: Compare other options

    Use object type parameter and check type inside method uses object and type checks, which is less clean. Create a base class Saveable and inherit from it uses inheritance, which is less flexible. Write separate methods for each class type duplicates code.
  4. Final Answer:

    Define an interface ISaveable with method Save(), then accept ISaveable parameter -> Option A
  5. Quick Check:

    Interfaces enable flexible method parameters [OK]
Quick Trick: Use interface parameters for flexible method inputs [OK]
Common Mistakes:
MISTAKES
  • Using object and type checks instead of interfaces
  • Relying only on inheritance
  • Writing duplicate methods for each type

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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