/ C#

.NET Quiz Question: Iterating Stack

One more .NET question. You probably know that IEnumerable<T> can be iterated by using foreach. It gets enumerator and runs through it from the first item to the last. For many collections the first item is which was added first. What about iterating Stack<T>? Do you know what the following code will print:

using System;
using System.Collections.Generic;

class Program
    public static void Main(string[] args)
        var list = new List<int>();
        foreach (var i in (IEnumerable<int>)list)

        var stack = new Stack<int>();
        foreach (var i in (IEnumerable<int>)stack)

Answer: this code prints list's items from first to last and stack's items from last added to first added, e.g. 101 102 102 101.

Alex Netkachov

Alex Netkachov

Alex Netkachov is a Senior Software Developer, currently working in Central London on new generation of energy trading solutions for brokers, traders and exchanges.

Read More

Why not to chat about this post? Join Telegram group Alex@Net or message on Twitter to alex_at_net. Alternatively, use the comments form below.