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:
Step 1: Understand interface benefits
Interfaces allow different classes to share a common method signature, enabling polymorphism.
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.
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.
Final Answer:
Define an interface ISaveable with method Save(), then accept ISaveable parameter -> Option A
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
Master "Interfaces" in C Sharp (C#)
9 interactive learning modes - each teaches the same concept differently