/ 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>();
        stack.Add(101);
        stack.Add(102);
        foreach (var i in (IEnumerable<int>)list)
            Console.WriteLine(i);

        var stack = new Stack<int>();
        stack.Push(101);
        stack.Push(102);
        foreach (var i in (IEnumerable<int>)stack)
            Console.WriteLine(i);
    }
}

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 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.