Difficulty: Easy
Correct Answer: 4
Explanation:
Introduction / Context:
Understanding how enumeration works in .NET collections is essential for writing thread-aware code. Each call to GetEnumerator() on a collection such as ArrayList returns a new enumerator object that maintains its own iteration state. When multiple threads enumerate the same collection concurrently, the number of enumerators equals the number of active enumerations.
Given Data / Assumptions:
Concept / Approach:
ArrayList implements IEnumerable and returns an IEnumerator via GetEnumerator(). Every call produces a distinct enumerator instance with its own cursor and version check. Enumerators are not thread-safe; they are lightweight objects designed to be used by a single enumeration context.
Step-by-Step Solution:
Verification / Alternative check:
Create a test that calls GetEnumerator() multiple times on the same ArrayList and compare ReferenceEquals among the returned enumerators; each call yields a different object reference.
Why Other Options Are Wrong:
1 or 2 or 3 assumes enumerator sharing, which does not occur automatically. “Depends on a project setting” is incorrect; enumerator creation is defined by the framework, not by IDE settings.
Common Pitfalls:
Mutating the collection while enumerating causes InvalidOperationException because enumerators track the collection version. Also, enumerators are not thread-safe objects; if multiple threads need to enumerate, they should each have their own enumerator or coordinate access.
Final Answer:
4
Discussion & Comments