Complete C# Tutorial

Generics Stack<T> in C# – A Beginner’s Guide with Examples

📌 Introduction

Ever stacked books one on top of another? 📚 When you remove a book, you take the top one first, right? That’s exactly how Generics Stack<T> in C# works! It follows the LIFO (Last In, First Out) rule, meaning the last item added is the first to be removed.

Example: Think of an “undo” feature in a text editor. Each action is stored in a stack, and when you press “undo,” the last action gets removed first! 🎯

🚀 What is Generics Stack<T> in C#?

A Stack<T> is a collection in C# that follows the LIFO (Last In, First Out) principle.

💡 Think of a stack of plates at a buffet – you place a new plate on top, and when you take one, you remove the topmost plate first!

👉 In C#, Stack<T> is present inside the System.Collections.Generic namespace.

🔍 Syntax of Generics Stack<T> in C#

Here’s how you declare a Stack<T> in C#:

				
					Stack<T> stackName = new Stack<T>();
				
			
  1. T is the data type (like int, string, double, etc.).
  2. stackName is the name of the stack.

🎯 Example 1: Creating and Using a Stack<T> in C#

				
					using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Creating a stack of integers
        Stack<int> numbers = new Stack<int>();

        // Adding elements (Push)
        numbers.Push(10);
        numbers.Push(20);
        numbers.Push(30);

        Console.WriteLine("Top element (Peek): " + numbers.Peek()); // Output: 30

        // Removing element (Pop)
        Console.WriteLine("Removed: " + numbers.Pop()); // Output: 30

        // Display remaining elements
        Console.WriteLine("Stack count: " + numbers.Count); // Output: 2
    }
}
				
			

📌 Explanation:

  1. We created a stack of integers.

  2. We added elements using Push().

  3. We checked the top element using Peek().

  4. We removed the top element using Pop().

  5. Finally, we displayed the number of remaining elements.

📌 Output:

				
					Top element (Peek): 30
Removed: 30
Stack count: 2
				
			

🔥 Important Methods of Stack<T> in C#

MethodDescriptionExample
Push(T item)Adds an item to the stack.stack.Push(5);
Pop()Removes and returns the top item.int item = stack.Pop();
Peek()Returns the top item without removing it.int top = stack.Peek();
CountGets the number of elements.int count = stack.Count;
Contains(T item)Checks if an item exists in the stack.stack.Contains(20);
Clear()Removes all elements.stack.Clear();

💡 Example 2: Checking if an Item Exists in Stack

				
					using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Stack<string> names = new Stack<string>();
        names.Push("Alice");
        names.Push("Bob");
        names.Push("Charlie");

        if (names.Contains("Bob"))
        {
            Console.WriteLine("Bob is in the stack!");
        }
    }
}
				
			

📌 Output:

				
					Bob is in the stack!
				
			

🌍 Real-World Example: Web Browser History

Ever used the back button in a web browser? Every page you visit gets stored in a stack. When you click “Back,” the last visited page is removed and displayed again!

 

💻 Simulating Browser History Using Stack<T> in C#

				
					using System;
using System.Collections.Generic;

class BrowserHistory
{
    static void Main()
    {
        Stack<string> history = new Stack<string>();

        history.Push("Home Page");
        history.Push("About Page");
        history.Push("Contact Page");

        Console.WriteLine("Current page: " + history.Peek()); // Contact Page

        Console.WriteLine("Going back...");
        history.Pop(); // Removes Contact Page

        Console.WriteLine("Now at: " + history.Peek()); // About Page
    }
}
				
			

📌 Output:

				
					Current page: Contact Page
Going back...
Now at: About Page
				
			

🎯 Why is Generics Stack<T> in C# Important?

  1. Follows LIFO (Last In, First Out) – Perfect for undo/redo operations.
  2. Fast operations – Push and Pop are quick.
  3. Used in real-world applications like browser history, recursion, and expression evaluation.

💡 Example 3: Reversing a String Using Stack<T> in C#

				
					using System;
using System.Collections.Generic;

class ReverseString
{
    static void Main()
    {
        string input = "HELLO";
        Stack<char> stack = new Stack<char>();

        foreach (char c in input)
        {
            stack.Push(c);
        }

        Console.Write("Reversed: ");
        while (stack.Count > 0)
        {
            Console.Write(stack.Pop());
        }
    }
}
				
			

📌 Output:

				
					Reversed: OLLEH
				
			

🎯 Conclusion

Awesome! Now you fully understand how Generics Stack<T> in C# works. 🎉

➡️ You learned the LIFO (Last In, First Out) principle.
➡️ You saw how to add, remove, and peek elements in a stack.
➡️ You explored real-world applications like browser history and undo/redo.
➡️ We covered important Stack<T> methods with examples.

Stacks are super powerful in C#. Practice by writing your own programs to get better at using them! 🚀

 

Next What?

You’re doing amazing! 💡 Ready to move forward?

👉 In the next chapter, you will learn about Generics HashSet<T> in C#, which helps store unique elements only!

 

🔥 Stay curious, keep coding, and have fun! 🚀 Let me know if you have any doubts! 😃

Leave a Comment

Share this Doc

Generic Stack<T>

Or copy link