0
0
CsharpHow-ToBeginner · 3 min read

How to Use Stack in C#: Syntax, Example, and Tips

In C#, use the Stack<T> class to store items in a last-in, first-out (LIFO) order. You can add items with Push(), remove the top item with Pop(), and look at the top item without removing it using Peek().
📐

Syntax

The Stack<T> class is a generic collection that stores elements in LIFO order. Here are the main methods:

  • Push(T item): Adds an item to the top of the stack.
  • Pop(): Removes and returns the top item.
  • Peek(): Returns the top item without removing it.
  • Count: Property to get the number of items.
csharp
Stack<int> stack = new Stack<int>();
stack.Push(10);       // Add 10
int top = stack.Peek(); // Look at top item
int removed = stack.Pop(); // Remove top item
int count = stack.Count;  // Number of items
💻

Example

This example shows how to create a stack, add items, peek at the top item, and remove items until the stack is empty.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Stack<string> stack = new Stack<string>();

        // Add items
        stack.Push("apple");
        stack.Push("banana");
        stack.Push("cherry");

        // Peek at the top item
        Console.WriteLine("Top item: " + stack.Peek());

        // Remove items
        while (stack.Count > 0)
        {
            Console.WriteLine("Popped: " + stack.Pop());
        }
    }
}
Output
Top item: cherry Popped: cherry Popped: banana Popped: apple
⚠️

Common Pitfalls

Common mistakes when using Stack<T> include:

  • Calling Pop() or Peek() on an empty stack causes an InvalidOperationException.
  • Forgetting that Stack is LIFO, so the last item added is the first removed.
  • Using Count to check if the stack is empty before popping or peeking.
csharp
Stack<int> stack = new Stack<int>();

// Wrong: popping without checking if empty
// int item = stack.Pop(); // Throws exception

// Right: check before popping
if (stack.Count > 0)
{
    int item = stack.Pop();
}
📊

Quick Reference

Method/PropertyDescription
Push(T item)Add item to the top of the stack
Pop()Remove and return the top item
Peek()Return the top item without removing it
CountGet the number of items in the stack
Clear()Remove all items from the stack
Contains(T item)Check if an item exists in the stack

Key Takeaways

Use Stack to store items in last-in, first-out order in C#.
Always check Count before calling Pop or Peek to avoid exceptions.
Push adds items, Pop removes the top item, and Peek views the top item without removing.
Stack is useful for undo operations, parsing, and backtracking scenarios.
Use Clear() to empty the stack and Contains() to check for an item.