/ 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 likes functional programming, algorithms and code reviews. Apart from programming, his favourites are walking with his family in the parks and national trails and reading books.

Read More

Why not to stay updated if the subject is interesting? Join Telegram channel Alex@Net or follow alex_at_net on Twitter. Or just, use the comments form below.