← Back to C# Course | Chapter 9: Collections | Lesson 5 of 7

Queue and Stack

In this page:

  1. Queue and Stack

Queue and Stack

Queue<T> is a first-in-first-out collection using Enqueue/Dequeue, while Stack<T> is last-in-first-out using Push/Pop. Queues model things like task processing order; stacks model things like undo history or recursive call tracking. Both throw an exception if you try to remove from an empty collection.

Note: Think "line at a store" for Queue and "plates stacked on top of each other" for Stack.

Example: Queue and Stack

markup
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Queue<string> line = new Queue<string>();
        line.Enqueue("first");
        line.Enqueue("second");
        Console.WriteLine(line.Dequeue());

        Stack<string> history = new Stack<string>();
        history.Push("page1");
        history.Push("page2");
        Console.WriteLine(history.Pop());
    }
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.