The Stack
collection in C# is a data structure that stores items in a Last-In-First-Out (LIFO) order. It’s ideal for scenarios where the last item added is the first one to be removed, such as reversing operations, managing states, or backtracking. In this tutorial, we’ll explore the Stack
in C#, understand its functionality through examples, discuss use cases, and illustrate its practicality with a real-world example.
In C#, the Stack
class is part of the System.Collections.Generic
namespace and provides a way to store data in a LIFO order. When an item is added to the stack, it’s placed on the "top". To retrieve or remove an item, only the most recently added (top) item is accessible. Stacks are helpful for specific types of tasks where this LIFO behavior aligns with the requirement, such as managing undo operations in an application or performing depth-first search in algorithms.
You can initialize a Stack
in C# with or without initial values. Here’s a simple example of creating an empty stack and one initialized with values.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creating an empty Stack of integers
Stack<int> numberStack = new Stack<int>();
// Initializing a Stack with values
Stack<string> fruitStack = new Stack<string>(new string[] { "Apple", "Banana", "Cherry" });
Console.WriteLine("Stack created with initial fruits:");
foreach (var fruit in fruitStack)
{
Console.WriteLine(fruit);
}
}
}
Push
)The Push
method adds an element to the top of the stack.
numberStack.Push(10);
numberStack.Push(20);
numberStack.Push(30);
Peek
)The Peek
method allows you to see the top element without removing it from the stack.
int topElement = numberStack.Peek(); // Output: 30
Console.WriteLine($"Top element: {topElement}");
Pop
)The Pop
method removes and returns the top element from the stack.
int removedElement = numberStack.Pop(); // Output: 30
Console.WriteLine($"Removed element: {removedElement}");
Stack
can be used to store a sequence of operations that allow users to undo or redo their actions.A typical use case for a stack is managing browser history. Each time a user navigates to a new page, the current page is pushed onto the history stack. When the user clicks “Back,” the last page visited is “popped” from the stack and displayed.
using System;
using System.Collections.Generic;
class BrowserHistory
{
private Stack<string> historyStack = new Stack<string>();
public void VisitPage(string url)
{
historyStack.Push(url);
Console.WriteLine($"Visited: {url}");
}
public void Back()
{
if (historyStack.Count > 1)
{
historyStack.Pop(); // Pop the current page
string previousPage = historyStack.Peek(); // Peek to get the previous page
Console.WriteLine($"Back to: {previousPage}");
}
else
{
Console.WriteLine("No previous pages to go back to.");
}
}
public void ShowHistory()
{
Console.WriteLine("\nBrowser History:");
foreach (var page in historyStack)
{
Console.WriteLine(page);
}
}
}
class Program
{
static void Main()
{
BrowserHistory browserHistory = new BrowserHistory();
// Visiting pages
browserHistory.VisitPage("www.homepage.com");
browserHistory.VisitPage("www.section.com");
browserHistory.VisitPage("www.article.com");
// Going back
browserHistory.Back();
// Show the current history
browserHistory.ShowHistory();
}
}
Using a stack in this scenario makes it easy to implement backtracking functionality, giving users a smooth experience when navigating through pages.
Push
to add, Pop
to remove, and Peek
to view the top element without removal.The Stack
in C# is a straightforward yet powerful data structure, essential for scenarios requiring LIFO ordering. Its operations, such as Push
, Pop
, and Peek
, offer an efficient way to manage temporary data. From managing browser history to implementing undo actions, Stack
provides a practical solution to numerous common programming challenges. Understanding how to apply Stack
effectively can help developers simplify complex state management tasks in a variety of applications.