C#.NET generics — Which statement correctly states an advantage of generics?

Difficulty: Easy

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 (generic): List avoids casts and boxing, and catches type mistakes at compile time.



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.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion