liveBook · Manning

Immutable stack

As explained in C# Concurrency: Asynchronous and multithreaded programming

An immutable stack is a last-in, first-out collection whose push and pop operations produce new stack versions without changing existing versions.

An immutable stack is a last-in, first-out collection whose operations return new versions instead of changing existing ones. A linked top node points to the previous stack state, allowing each version to remain available. section 13.3.1

The implementation exposes three core behaviors:

  • Push returns a new stack containing the item above the previous top. section 13.3.1
  • Pop returns the top value and a new stack whose top is the previous node’s successor. section 13.3.1
  • IsEmpty reports whether the stack has a top node. section 13.3.1

Versioned pushes and pop

Create stack1, derive stack2 with Push(1), derive stack3 with Push(2), then derive stack4 with Pop(out item). The earlier versions remain distinct. section 13.3.1

Listing 13.15 Immutable stack implementation
public class MyImmutableStack<T>
{
  private record class StackItem(T Value, StackItem Next);
  private readonly StackItem? _top;
  public MyImmutableStack() {}
  private MyImmutableStack(StackItem? top)
  {
     _top = top;
  }
  public MyImmutableStack<T> Push(T item)
  {
     return new MyImmutableStack<T>(new StackItem(item,_top); 
  }
  public MyImmutableStack<T> Pop(out T? item)
  {
     if(_top == null)
        throw new InvalidOperationException("Stack is empty");
     item = _top.Value;
     return new MyImmutableStack<T>(_top.Next);
  }
  public bool IsEmpty => _top == null;
}

Inspect the complete C# implementation built from a nullable top reference and nested StackItem records. section 13.3.1

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains push, pop, emptiness, and linked-node state transitions through a complete C# implementation.
Examples
Uses a two-value push/pop sequence and contrasts it with a ten-item lock-protected array stack.
What it assumes
Assumes basic C# and stack terminology while establishing the mutable array-stack comparison before the immutable design.
What you can do after
Build it from scratch in C# using version-returning Push and Pop operations over linked stack nodes.
How it connects
Connects immutable collections with stacks, arrays, locks, and linked nodes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.