System.Collections.Generic.Stack<T> Class

Namespace: System.Collections.Generic

Represents a collection of objects that can be accessed by index. Thelastobject added to theStackis thefirstone that is removed.

Table of Contents

Constructors

Properties

Methods

Examples

C# Example
using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new stack of strings
        Stack<string> myStack = new Stack<string>();

        // Push elements onto the stack
        myStack.Push("Apple");
        myStack.Push("Banana");
        myStack.Push("Cherry");

        // Get the number of elements
        Console.WriteLine($"Stack count: {myStack.Count}"); // Output: Stack count: 3

        // Peek at the top element
        Console.WriteLine($"Top element: {myStack.Peek()}"); // Output: Top element: Cherry

        // Pop elements from the stack
        while (myStack.Count > 0)
        {
            string item = myStack.Pop();
            Console.WriteLine($"Popped: {item}");
        }
        // Output:
        // Popped: Cherry
        // Popped: Banana
        // Popped: Apple

        // Check if stack is empty
        Console.WriteLine($"Stack is empty: {myStack.Count == 0}"); // Output: Stack is empty: True
    }
}