How Stack Works in C#: Push, Pop, Peek, and More



In programming, data structures play an essential role in managing and organizing data efficiently. One such important data structure is the C# Stack, which is widely used in algorithms, memory management, expression evaluation, navigation history, and more. In C#, the Stack is implemented in the System.Collections.Generic namespace and follows the LIFO (Last In, First Out) mechanism.

This article will help you understand how Stack works in C#, its key operations such as Push, Pop, Peek, and common use cases with real examples.

What is a Stack in C#?

A Stack is a linear data structure where the element added most recently is removed first. It works just like a stack of books—only the top book can be removed or viewed.

LIFO Principle

  • Last In → First Out

  • The most recently inserted item is always processed first

Example in real life:

  • Browser history navigation (Back button)

  • Undo/Redo operations in editors

  • Function call stack in programming

Creating a Stack in C#

To use Stack, first include the required namespace:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Stack<int> numbers = new Stack<int>();
    }
}

Here, we created a Stack of integers using Stack. You can also create stacks of strings, objects, or custom classes.

Stack Operations in C#

1. Push() – Add an element

The Push() method inserts an item at the top of the stack.

Stack<string> names = new Stack<string>();
names.Push("Amit");
names.Push("Priya");
names.Push("Rohan");

After these operations, the stack contains:

Top → Rohan, Priya, Amit

2. Pop() – Remove and return the top element

The Pop() method removes the item at the top and returns it.
It throws an exception if the stack is empty.

string item = names.Pop();
Console.WriteLine("Removed: " + item);

Output:

Removed: Rohan

Updated stack:

Top → Priya, Amit

3. Peek() – View the top element

The Peek() method returns the top element without removing it.

Console.WriteLine("Top element: " + names.Peek());

Output:

Top element: Priya

4. Count Property

Shows the number of elements in the stack.

Console.WriteLine("Total elements: " + names.Count);

5. Contains() – Search element

Checks whether an item is present.

Console.WriteLine(names.Contains("Amit"));  // true

6. Clear() – Remove all elements

names.Clear();

Complete Example of Stack in C#

using System;
using System.Collections.Generic;

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

        stack.Push(10);
        stack.Push(20);
        stack.Push(30);

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

        Console.WriteLine("Removed: " + stack.Pop());
        Console.WriteLine("After Pop, Top: " + stack.Peek());

        Console.WriteLine("Total Items: " + stack.Count);

        Console.WriteLine(stack.Contains(20) ? "Found!" : "Not Found!");
    }
}

Output:

Top Element: 30
Removed: 30
After Pop, Top: 20
Total Items: 2
Found!

Real-World Use Cases of Stack

Use Case Explanation
Browser History Back navigation uses stack to store visited pages
Undo/Redo Text editors store actions in stack
Expression Evaluation Converting infix to postfix & evaluating expressions
Recursion Maintains function call stack
Tree & Graph Traversal Used in DFS (Depth-First Search)

Advantages of Stack

  • Simple and easy to implement

  • Fast push and pop operations (O(1) time complexity)

  • Useful for memory management and solving complex problems

Disadvantages

  • Limited access – only top element can be accessed

  • Not suitable for searching or random access

Stack vs Queue

Feature Stack Queue
Mechanism LIFO FIFO
Remove First Last inserted First inserted
Example Browser history Printer jobs

Conclusion

Stack is a very powerful and commonly used data structure in C#. It works on the LIFO principle and provides operations like Push, Pop, Peek, Count, and Contains to efficiently manage data. Whether you’re building navigation controls, algorithm logic, or application undo/redo features, Stack plays an important role in solving real-world problems.

Learning Stack not only helps you understand data handling but also improves your problem-solving and algorithmic thinking.


Comments

Popular posts from this blog

Quantitative Aptitude Questions and Answers with Solutions for Beginners

What is a PHP Developer? Roles, Skills, and Career Guide

Java Tutorial: Master Object-Oriented Programming