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

Queue and Stack

A Queue is a line at a shop where the first person in is served first, while a Stack is a pile of plates where the last one placed on top is taken first. Each has its own order for taking things out.

In this page:

  1. Queue and Stack
Syntax
csharp
Queue<type> queue = new Queue<type>();
queue.Enqueue(item);
queue.Dequeue();   // first in, first out

Stack<type> stack = new Stack<type>();
stack.Push(item);
stack.Pop();       // last in, first out

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());
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Calling Pop or Dequeue on an empty collection, which throws InvalidOperationException.
  2. Mixing up order: a stack is last in, first out and a queue is first in, first out.
  3. Using Peek and expecting it to remove the item.
🔒

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.