C# Stack

Introduction

The Stack<T> class in C# represents a last-in, first-out (LIFO) collection of objects. It is part of the System.Collections.Generic namespace and is useful when you need to reverse the order of items or when the most recently added item is the first one to be removed. The Stack<T> class provides methods to push, pop, and peek at items, ensuring efficient management of LIFO collections.

Key Features of Stack

  • LIFO Order: Last-in, first-out ordering of elements.
  • Dynamic Size: Automatically resizes as elements are added or removed.
  • Type Safety: Enforces type safety, ensuring that all elements are of the specified type T.
  • Rich API: Includes methods for pushing, popping, and peeking at elements.

Creating a Stack

Declaration and Initialization

You can declare and initialize a Stack<T> in several ways:

Example

using System;
using System.Collections.Generic;

namespace StackExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating an empty stack
            Stack<int> numbers = new Stack<int>();

            // Creating a stack with initial elements
            Stack<string> fruits = new Stack<string>();
            fruits.Push("Apple");
            fruits.Push("Banana");
            fruits.Push("Cherry");

            // Displaying elements
            Console.WriteLine("Fruits in stack:");
            foreach (string fruit in fruits)
            {
                Console.WriteLine(fruit);
            }
        }
    }
}

Output

Fruits in stack:
Cherry
Banana
Apple

Common Operations on Stack

Pushing Elements

  • Push: Adds an element to the top of the stack.
numbers.Push(1);
numbers.Push(2);
numbers.Push(3);

Popping Elements

  • Pop: Removes and returns the element at the top of the stack. Throws an InvalidOperationException if the stack is empty.
int topNumber = numbers.Pop(); // 3

Peeking at Elements

  • Peek: Returns the element at the top of the stack without removing it. Throws an InvalidOperationException if the stack is empty.
int topNumber = numbers.Peek(); // 2

Checking the Stack Size

  • Count: Gets the number of elements in the stack.
int count = numbers.Count; // 2

Clearing the Stack

  • Clear: Removes all elements from the stack.
numbers.Clear();

Practical Example

Let’s create a practical example where we use a Stack<T> to manage a history of actions in an application, allowing the user to undo the last action.

Example

using System;
using System.Collections.Generic;

namespace ActionHistoryExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack<string> actions = new Stack<string>();

            // Performing actions
            PerformAction(actions, "Open File");
            PerformAction(actions, "Edit File");
            PerformAction(actions, "Save File");

            // Undoing the last action
            UndoLastAction(actions);

            // Displaying remaining actions
            Console.WriteLine("Remaining actions in history:");
            foreach (string action in actions)
            {
                Console.WriteLine(action);
            }
        }

        static void PerformAction(Stack<string> actions, string action)
        {
            actions.Push(action);
            Console.WriteLine($"Performed action: {action}");
        }

        static void UndoLastAction(Stack<string> actions)
        {
            if (actions.Count > 0)
            {
                string lastAction = actions.Pop();
                Console.WriteLine($"Undid action: {lastAction}");
            }
            else
            {
                Console.WriteLine("No actions to undo.");
            }
        }
    }
}

Output

Performed action: Open File
Performed action: Edit File
Performed action: Save File
Undid action: Save File
Remaining actions in history:
Edit File
Open File

Conclusion

The Stack<T> class in C# provides a simple and efficient way to manage collections of items in a last-in, first-out (LIFO) order. It is ideal for scenarios where you need to reverse the order of items or ensure that the most recently added item is the first one to be removed. Understanding how to use Stack<T> effectively can help you manage collections of data in your applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top