0
0
CsharpHow-ToBeginner · 3 min read

How to Implement Stack in C#: Syntax and Example

In C#, you can implement a stack using the built-in Stack<T> class which provides methods like Push, Pop, and Peek. This class works like a real-life stack where you add and remove items in a last-in, first-out order.
📐

Syntax

The Stack<T> class is a generic collection that stores elements in a last-in, first-out (LIFO) order. You create a stack by specifying the type of elements it will hold inside angle brackets <>. Key methods include:

  • Push(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.
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
💻

Example

This example shows how to create a stack of strings, add items, check the top item, and remove items while printing the results.

csharp
using System;
using System.Collections.Generic;

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

        stack.Push("apple");
        stack.Push("banana");
        stack.Push("cherry");

        Console.WriteLine("Top item: " + stack.Peek());

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

Common Pitfalls

Common mistakes when using stacks include:

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

Always check stack.Count > 0 before removing or peeking to avoid errors.

csharp
Stack<int> stack = new Stack<int>();

// Wrong: causes exception if stack is empty
// int item = stack.Pop();

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

Quick Reference

MethodDescription
Push(item)Add item to the top of the stack
Pop()Remove and return the top item
Peek()Return the top item without removing
CountGet the number of items in the stack
Clear()Remove all items from the stack

Key Takeaways

Use the generic Stack class to implement a stack in C# easily.
Push adds items, Pop removes the last added item, and Peek views the top item without removing it.
Always check if the stack is not empty before calling Pop or Peek to avoid exceptions.
Stack works in last-in, first-out order, like a real stack of plates.
Use Count property to know how many items are currently in the stack.