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 You Are Going to Learn in This Lesson
✔️ What is Generics Stack<T> in C# and why is it important?
✔️ How LIFO (Last In, First Out) works.
✔️ Basic syntax and how to create a Stack<T>.
✔️ Important methods like Push()
, Pop()
, Peek()
, and Count()
.
✔️ Real-world examples where Stack<T> is used.
✔️ Complete C# programs with output to help you understand better.
🚀 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>();
T
is the data type (likeint
,string
,double
, etc.).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:
We created a stack of integers.
We added elements using
Push()
.We checked the top element using
Peek()
.We removed the top element using
Pop()
.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#
Method | Description | Example |
---|---|---|
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(); |
Count | Gets 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?
- Follows LIFO (Last In, First Out) – Perfect for undo/redo operations.
- Fast operations – Push and Pop are quick.
- 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! 😃