Generics in C#.NET — For a generic class SortObjects that must compare any type (int, float, byte, etc.), which construct should be used to implement the comparison function cleanly and type-safely?
-
ANamespace
-
BInterface
-
CEncapsulation
-
DDelegate
-
EAttribute
Answer
Correct Answer: Interface
Explanation
Introduction / Context:Sorting arbitrary objects generically in C#.NET requires a type-safe way to compare two instances. The question asks which construct best provides a reusable comparison contract for any T.
Given Data / Assumptions:
- The class SortObjects should sort values of many types.
- We want a design that works across the .NET type system.
- Solutions should be type-safe and extensible.
Concept / Approach:Interfaces such as IComparable
Step-by-Step Solution:
Define SortObjects.Sort using IComparerVerification / Alternative check:Use built-in List
Why Other Options Are Wrong:
- Namespace/Attribute: metadata/organization concepts, not behavioral contracts.
- Encapsulation: a principle, not a comparison API.
- Delegate: useful for ad-hoc comparisons, but the long-term, reusable contract for generic sorting is via interfaces.
Common Pitfalls:Hard-coding comparisons for each type or using object and casting, which sacrifices type safety.
Final Answer:Interface