WeCodeAcademy

C# Stack, Queue and HashSet

Besides List and Dictionary, C# has a Stack (last in, first out), a Queue (first in, first out) and a HashSet (unique values).

ExampleC#
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Stack<int> stack = new Stack<int>();
        stack.Push(1);
        stack.Push(2);
        stack.Push(3);
        Console.WriteLine(stack.Pop());
        Console.WriteLine(stack.Peek());

        Queue<string> queue = new Queue<string>();
        queue.Enqueue("first");
        queue.Enqueue("second");
        Console.WriteLine(queue.Dequeue());
        Console.WriteLine(queue.Count);

        HashSet<int> set = new HashSet<int> { 3, 1, 3, 2, 1 };
        Console.WriteLine(set.Count);
        Console.WriteLine(set.Contains(2));
    }
}
Output
3
2
first
1
3
True
Quick check

Which collection returns the most recently added item first?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.