C# `Stack` Class: Implementing Last-In, First-Out (LIFO) Data Structures

Learn how to use C#'s `Stack` class to efficiently manage Last-In, First-Out (LIFO) data. This tutorial covers key methods like `Push()`, `Pop()`, `Peek()`, and demonstrates practical examples of using stacks for various data handling tasks.



Working with the C# `Stack` Class

The C# `Stack` class is a collection that stores elements in a Last-In, First-Out (LIFO) order. Think of it like a stack of plates: you can only add or remove plates from the top.

Key Features of C# `Stack`

  • LIFO Order: The last element added is the first one removed.
  • Duplicate Elements Allowed: You can have multiple instances of the same element in a stack.
  • Namespace: `System.Collections.Generic` (for generic stacks).

Common `Stack` Methods

  • Push(item): Adds an element to the top of the stack.
  • Pop(): Removes and returns the element at the top of the stack. Throws an exception if the stack is empty.
  • Peek(): Returns the element at the top of the stack without removing it. Throws an exception if the stack is empty.
  • Iteration (using a `foreach` loop): Allows you to access each element in the stack from top to bottom.

Example: Using a Generic Stack


using System;
using System.Collections.Generic;

public class StackExample {
    public static void Main(string[] args) {
        Stack<string> names = new Stack<string>();
        // ... (code to push elements, iterate, peek, and pop) ...
    }
}

Explanation

The example creates a stack of strings, adds several names using `Push()`, iterates through the stack using a `foreach` loop, uses `Peek()` to view the top element, and then uses `Pop()` to remove and display the top element. The output shows the order in which the elements are processed (LIFO).