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

C# Programming Collection Classes Difficulty: Easy
Choose an option
  • A
    IEnumerable e = st.GetEnumerator(); while (e.MoveNext()) Console.WriteLine(e.Current);
  • B
    IEnumerator e = st.GetEnumerable(); while (e.MoveNext()) Console.WriteLine(e.Current);
  • C
    IEnumerator e = st.GetEnumerator(); while (e.MoveNext()) Console.WriteLine(e.Current);
  • D
    IEnumerator e = Stack.GetEnumerator(); while (e.MoveNext()) Console.WriteLine(e.Current);
  • E
    Use st[0]…st[n] since Stack is index-based.

Answer

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

Explanation

Introduction / Context:Like Queue, Stack supports enumeration through GetEnumerator(). Understanding iteration without indexing is important for LIFO containers.

Concept / Approach:Call st.GetEnumerator(), loop with MoveNext(), and access Current. Alternatively, foreach (var x in st) is the idiomatic approach.

Why Other Options Are Wrong:Option A: Type mismatch (GetEnumerator returns IEnumerator). Option B: GetEnumerable() does not exist. Option D: GetEnumerator is not static. Option E: Stack is not index-based.

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

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