Stack

Intro

Stack<T> is a LIFO (last in, first out) collection. The most recently pushed element is the first popped. Use it for backtracking, undo flows, and depth-first traversals.

Stack<T> in .NET is array-backed and optimized for top-of-stack operations:

The runtime uses a call stack with the same LIFO discipline: each function invocation pushes a stack frame containing its local variables and return address; when the function returns, the frame is popped. An explicit Stack<T> mirrors this behavior in application code — useful for undo/redo chains, expression evaluation, and depth-first backtracking without the recursion limit risk. Unlike the implicit call stack, Stack<T> capacity is bounded only by heap memory.

Structure

graph TD
    T[top] --> N3[item c]
    N3 --> N2[item b]
    N2 --> N1[item a]
    N1 --> B[bottom]

Example

var stack = new Stack<string>();
stack.Push("A");
stack.Push("B");

Console.WriteLine(stack.Peek()); // B
Console.WriteLine(stack.Pop());  // B
Console.WriteLine(stack.Pop());  // A

Pitfalls

Tradeoffs

Questions

Stack class — API reference covering Push, Pop, Peek, and enumeration order.
  • Selecting a collection class — Microsoft decision guide for choosing between Stack, Queue, and other collection types.
  • Generic collections in .NET — overview of all generic collection types with complexity and usage guidance.
  • Stack implementation in dotnet runtime — source code showing the internal array and resize logic.

  • Whats next

    Parent
    02 Computer Science

    Pages