0
0
CsharpConceptBeginner · 3 min read

What is Stack in C#: Explanation and Example

In C#, a Stack is a collection that stores items in a last-in, first-out (LIFO) order. You add items with Push() and remove them with Pop(), making it useful for tasks like undo operations or expression evaluation.
⚙️

How It Works

A Stack in C# works like a stack of plates in your kitchen. You put a plate on top, and when you need one, you take the top plate off first. This means the last item you added is the first one you get back, which is called last-in, first-out (LIFO).

When you add an item, you use the Push() method to place it on top of the stack. To remove the top item, you use Pop(). You can also look at the top item without removing it using Peek(). This structure is simple but very useful for managing data where order matters in this way.

💻

Example

This example shows how to create a stack, add items, and remove them while printing the results.

csharp
using System;
using System.Collections.Generic;

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

        stack.Push("First");
        stack.Push("Second");
        stack.Push("Third");

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

        while (stack.Count > 0)
        {
            Console.WriteLine("Popped: " + stack.Pop());
        }
    }
}
Output
Top item: Third Popped: Third Popped: Second Popped: First
🎯

When to Use

Use a Stack when you need to reverse the order of items or keep track of the most recent item added. Common uses include:

  • Undo features in text editors or apps, where the last action is undone first.
  • Parsing expressions in calculators or compilers.
  • Backtracking algorithms, like navigating mazes or puzzles.

Stacks are simple and fast for these tasks because they only add or remove items from one end.

Key Points

  • Stack follows last-in, first-out (LIFO) order.
  • Use Push() to add and Pop() to remove items.
  • Peek() lets you see the top item without removing it.
  • Ideal for undo operations, expression evaluation, and backtracking.

Key Takeaways

A Stack in C# stores items in last-in, first-out order.
Use Push() to add and Pop() to remove the top item.
Peek() lets you check the top item without removing it.
Stacks are great for undo features and expression parsing.