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
-
AIEnumerable e = st.GetEnumerator(); while (e.MoveNext()) Console.WriteLine(e.Current);
-
BIEnumerator e = st.GetEnumerable(); while (e.MoveNext()) Console.WriteLine(e.Current);
-
CIEnumerator e = st.GetEnumerator(); while (e.MoveNext()) Console.WriteLine(e.Current);
-
DIEnumerator e = Stack.GetEnumerator(); while (e.MoveNext()) Console.WriteLine(e.Current);
-
EUse 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);