Reuse mechanisms in C#.NET: which of the following provide code reuse in typical C# design? 1) Inheritance 2) Encapsulation 3) Templates 4) Containership (composition/aggregation) 5) Polymorphism
-
A1, 4
-
B1, 3
-
C2, 4
-
D3, 5
-
ENone of these
Answer
Correct Answer: 1, 4
Explanation
Introduction / Context:Code reuse is a principal OO goal. In C#, the most common reuse mechanisms are inheritance (specialization and reuse of base behavior) and containership/composition (reusing existing types as parts of larger types).
Given Data / Assumptions:
- “Templates” here maps to C++ terminology; in C#, the equivalent is generics, which facilitate type reuse but are not a direct code-reuse mechanism like inheritance/composition.
- Polymorphism enables substitutability but is built on inheritance/interfaces rather than being a reuse mechanism by itself.
- Encapsulation is about information hiding, not reuse per se.
Concept / Approach:Inheritance allows derived classes to reuse and extend base behavior. Containership (composition/aggregation) lets a class reuse existing classes by holding them as fields and delegating work. While generics and polymorphism are powerful, the classic “reuse mechanisms” are inheritance and composition.
Step-by-Step Solution:
Select 1 (inheritance) and 4 (containership).Reject 2 (encapsulation), 3 (templates in the C++ sense), and 5 (polymorphism) as primary reuse mechanisms.Verification / Alternative check:Review design patterns: composition-over-inheritance is a maxim precisely because both are established reuse techniques.
Why Other Options Are Wrong:They emphasize concepts that are important but either do not directly provide code reuse (encapsulation) or are language features/behaviors rather than reuse mechanisms (generics/polymorphism).
Common Pitfalls:Equating “polymorphism” with reuse; conflating C++ templates with C# generics and their role.
Final Answer:1, 4