Microsoft Docs

.NET API Documentation

Stack Class

System.Collections
Represents a simple, strongly typed, ordered collection of objects. This class provides methods for adding, removing, and accessing elements in a last-in, first-out (LIFO) order.

Constructors

Stack()
Initializes a new instance of the Stack class that is empty and has the default initial capacity or maximum size.
Stack(int capacity)
Initializes a new instance of the Stack class that is empty, has the specified initial capacity, and is randomly accessible.
Stack(ICollection c)
Initializes a new instance of the Stack class that contains elements copied from the specified collection and has enough capacity to accommodate the number of elements copied.

Methods

Method Description
Peek() : object Returns the object at the top of the Stack without removing it.
Pop() : object Removes and returns the object at the top of the Stack.
Push(object obj) : void Inserts an object at the top of the Stack.
Clear() : void Removes all objects from the Stack.
Clone() : object Creates a shallow copy of the Stack.
Contains(object obj) : bool Determines whether an element is in the Stack.
CopyTo(Array array, int index) : void Copies the entire Stack to a compatible one-dimensional Array, starting at the specified index of the target array.
GetEnumerator() : IEnumerator Returns an IEnumerator for the Stack.
Synchronized(Stack stack) : Stack Returns a synchronized wrapper for the specified Stack.

Properties

Property Description
Count : int Gets the number of elements contained in the Stack.
IsSynchronized : bool Gets a value indicating whether access to the Stack is synchronized (thread-safe).

Example

using System;
using System.Collections;

public class StackExample
{
    public static void Main(string[] args)
    {
        Stack myStack = new Stack();

        myStack.Push("Hello");
        myStack.Push("World");
        myStack.Push("!");

        Console.WriteLine("Stack elements:");
        foreach (object obj in myStack)
        {
            Console.WriteLine(obj);
        }

        Console.WriteLine("\nPopping elements:");
        while (myStack.Count > 0)
        {
            Console.WriteLine(myStack.Pop());
        }

        Console.WriteLine("\nStack count after popping: {0}", myStack.Count);
    }
}