TheAlgorithms/C-Sharp · error · InvalidOperationException
Stack is empty
Error message
Stack is empty
What it means
ListBasedStack<T>.Peek (backed by LinkedList<T>) returns the first element as the stack top. When the underlying list is empty (First is null) it throws InvalidOperationException with 'Stack is empty'.
Solutions
- Check stack.Count (or IsEmpty) before Peek.
- Use try/catch around InvalidOperationException when empty is expected.
- Restructure the loop so Peek is only called after at least one Push.
Example fix
// before var top = listStack.Peek(); // after var top = listStack.Count > 0 ? listStack.Peek() : default;
Defensive patterns
Strategy: validation
Validate before calling
if (listStack.Count == 0) return default;
Type guard
static bool TryPeek<T>(ListBasedStack<T> stack, out T value) { if (stack.Count > 0) { value = stack.Peek(); return true; } value = default; return false; } Try / catch
try { var top = listStack.Peek(); } catch (InvalidOperationException) { top = default; } Prevention
- Check Count/IsEmpty before Peek.
- Only Peek after at least one successful Push.
- Wrap Peek in Try-style helpers.
When it happens
Trigger: Calling Peek on an empty ListBasedStack — before any Push, or after all items were popped.
Common situations: Test code checking Peek on a fresh stack, iterative algorithms peeking between phases when the stack may have been fully consumed.
Related errors
AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13).
Data as JSON: /api/errors/187ce1f01319903d.
Report an issue: GitHub.
Appendix: source
Thrown at DataStructures/Stack/ListBasedStack.cs:64
/// </summary>
public void Clear() => stack.Clear();
/// <summary>
/// Determines whether an element is in the <see cref="ListBasedStack{T}" />.
/// </summary>
/// <param name="item">The item to locate in the <see cref="ListBasedStack{T}" />.</param>
/// <returns>True, if the item is in the stack.</returns>
public bool Contains(T item) => stack.Contains(item);
/// <summary>
/// Returns the item at the top of the <see cref="ListBasedStack{T}" /> without removing it.
/// </summary>
/// <returns>The item at the top of the <see cref="ListBasedStack{T}" />.</returns>
public T Peek()
{
if (stack.First is null)
{
throw new InvalidOperationException("Stack is empty");
}
return stack.First.Value;
}
/// <summary>
/// Removes and returns the item at the top of the <see cref="ListBasedStack{T}" />.
/// </summary>
/// <returns>The item removed from the top of the <see cref="ListBasedStack{T}" />.</returns>
public T Pop()
{
if (stack.First is null)
{
throw new InvalidOperationException("Stack is empty");
}
var item = stack.First.Value;
stack.RemoveFirst();View on GitHub (pinned to 96e2905cab)