Queue enumeration — choose the correct code to access all elements of a System.Collections.Queue instance.

C# Programming Collection Classes Difficulty: Easy
Choose an option
  • A
    IEnumerator e = q.GetEnumerator(); while (e.MoveNext()) Console.WriteLine(e.Current);
  • B
    IEnumerable e = q.GetEnumerator(); while (e.MoveNext()) Console.WriteLine(e.Current);
  • C
    IEnumerator e = q.GetEnumerable(); while (e.MoveNext()) Console.WriteLine(e.Current);
  • D
    IEnumerator e = Queue.GetEnumerator(); while (e.MoveNext()) Console.WriteLine(e.Current);
  • E
    Use foreach only; explicit enumerators are not supported.

Answer

Correct Answer: IEnumerator e = q.GetEnumerator(); while (e.MoveNext()) Console.WriteLine(e.Current);

Explanation

Introduction / Context:All non-generic collections in System.Collections support enumeration via IEnumerable/IEnumerator. Queue is no exception.

Concept / Approach:Call q.GetEnumerator() to get an IEnumerator. Iterate by calling MoveNext() and reading Current. foreach uses the same pattern behind the scenes.

Why Other Options Are Wrong:Option B: GetEnumerator() returns IEnumerator, not IEnumerable. Option C: GetEnumerable() does not exist. Option D: GetEnumerator() is an instance, not static, method. Option E: foreach is supported, but explicit IEnumerator use is also valid.

Final Answer:IEnumerator e = q.GetEnumerator(); while (e.MoveNext()) Console.WriteLine(e.Current);

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