C#.NET generics — Which statement correctly states an advantage of generics?
-
AGenerics shift the burden of type safety to the programmer rather than compiler.
-
BGenerics require use of explicit type casting.
-
CGenerics provide type safety without the overhead of multiple implementations.
-
DGenerics eliminate the possibility of run-time errors.
-
ENone of the above.
Answer
Correct Answer: Generics provide type safety without the overhead of multiple implementations.
Explanation
Introduction / Context:Generics in .NET enable strongly typed algorithms and collections without sacrificing performance or requiring a separate implementation for each type. This item asks for the primary benefit.
Given Data / Assumptions:
- We compare generics to non-generic collections and per-type hand-written classes.
- We consider compile-time type checking and boxing/unboxing avoidance.
Concept / Approach:Generics centralize an algorithm in a single implementation parameterized by type. The compiler enforces type safety, eliminating many casts. Because value types are stored without boxing in generic collections, performance improves. Generics do not make all runtime errors impossible, but they reduce a class of type-mismatch errors.
Step-by-Step Solution:
Select statement that reflects compile-time type safety with one implementation: option C.Reject A: Generics shift burden to the compiler, not the programmer.Reject B: Generics reduce or eliminate explicit casting in common scenarios.Reject D: You can still have runtime errors (e.g., null refs, IO failures).Verification / Alternative check:Compare ArrayList (non-generic) vs. List
Why Other Options Are Wrong:They contradict the fundamental purpose of generics or overclaim their guarantees.
Common Pitfalls:Assuming generics are merely syntactic sugar; they materially improve safety and performance.
Final Answer:Generics provide type safety without the overhead of multiple implementations.