Codectionary / Developer documentation / C#

Queue<T> & Stack<T>

Queue<T> is a first-in-first-out (FIFO) collection - items are added with Enqueue() and removed with Dequeue(), just like a real-world line. Stack<T> is last-in-first-out (LIFO) - items are added with Push() and removed with Pop(), like a stack of plates. Both are useful for specific processing orders where a general-purpose List<T> would require extra bookkeeping.

Syntax

Queue<Type> queue = new Queue<Type>();\nStack<Type> stack = new Stack<Type>();

Examples

Queue: First In, First Out

The first item added is the first one removed.

Queue<string> line = new Queue<string>();
line.Enqueue("Customer A");
line.Enqueue("Customer B");
line.Enqueue("Customer C");

Console.WriteLine(line.Dequeue());  // Customer A - first in, first out
Console.WriteLine(line.Peek());      // Customer B - look without removing
Console.WriteLine(line.Count);        // 2

Stack: Last In, First Out

The most recently added item is the first one removed.

Stack<string> history = new Stack<string>();
history.Push("Page 1");
history.Push("Page 2");
history.Push("Page 3");

Console.WriteLine(history.Pop());  // Page 3 - last in, first out
Console.WriteLine(history.Peek());  // Page 2 - look without removing

Practical Use: Balanced Parentheses Check

A classic use of Stack<T> for validating matched brackets.

bool IsBalanced(string input)
{
    Stack<char> stack = new Stack<char>();
    foreach (char c in input)
    {
        if (c == '(') stack.Push(c);
        else if (c == ')')
        {
            if (stack.Count == 0) return false;
            stack.Pop();
        }
    }
    return stack.Count == 0;
}

Console.WriteLine(IsBalanced("(a(b)c)"));  // true
Console.WriteLine(IsBalanced("(a(b)c"));    // false

Best practices

  • Use Queue<T> for FIFO processing like task scheduling or breadth-first traversal, and Stack<T> for LIFO needs like undo history or depth-first traversal
  • Use Peek() to inspect the next item without removing it, and TryDequeue()/TryPop() to avoid an exception when the collection might be empty
  • Prefer these purpose-built types over a List<T> with manual Insert(0, ...) or RemoveAt(list.Count - 1) - they are clearer in intent and more efficient
  • Remember both are still generic collections (Queue<T>, Stack<T>) - specify the element type just like with List<T>

At a glance

Purpose
Applications on the .NET platform
File extension
.cs
Runs in
.NET runtime
Usually used with
.NET SDK and libraries

Specifications & further reading

Related C# documentation

List<T>
List<T> is a resizable, generic collection from System.Collections.Generic, and the most commonly used collection type in C#. Unlike a plain array, a List<T> automatically grows as elements are added, and it provides a rich set of methods for adding, removing, searching, and sorting. The <T> means a List can be strongly typed to hold any specific type, like List<string> or List<int>.
Dictionary<TKey, TValue>
Dictionary<TKey, TValue> stores data as key-value pairs, offering fast average-case lookup, insertion, and deletion by key, backed by a hash table. Keys must be unique - adding a value with an existing key throws an exception, while indexer assignment (dict[key] = value) overwrites it instead. Dictionary does not guarantee any particular iteration order.
HashSet<T>
HashSet<T> is a collection that stores unique elements with no guaranteed ordering, backed by a hash table. Adding a duplicate element has no effect, since HashSet automatically enforces uniqueness. It provides very fast average-case performance for adding, removing, and checking membership, and offers built-in set operations like union, intersection, and difference.
foreach & IEnumerable
foreach is C#'s dedicated loop for iterating over any collection that implements IEnumerable<T> - which includes arrays, List<T>, Dictionary<TKey,TValue>, and virtually every built-in collection. Behind the scenes, foreach uses an enumerator (via GetEnumerator()) to walk through items one at a time. Any custom class can support foreach by implementing IEnumerable<T> itself.