MSDN .NET API Documentation

Stack<T> Class

Namespace: System.Collections.Generic

Represents a collection of objects that can be accessed by index. The last item added to the collection is the first item that must be accessed.

Inheritance

Remarks

The Stack<T> generic class provides a Last-In-First-Out (LIFO) collection of objects.

The Stack<T> class is not thread-safe. For a thread-safe version, see ConcurrentStack<T>.

The capacity of a Stack<T> is the number of elements the Stack<T> can hold. As elements are added to a Stack<T>, the capacity is automatically increased by reallocating the underlying array.

Elements are added to the top of the stack and removed from the top of the stack.

This implementation uses a zero-based indexed array.

Example

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        Stack<string> names = new Stack<string>();
        names.Push("Microsoft");
        names.Push("Visual");
        names.Push("Studio");

        Console.WriteLine("Pushing elements:");
        foreach (string name in names)
        {
            Console.WriteLine(name);
        }

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

        Console.WriteLine("\nElements after popping:");
        Console.WriteLine(names.Count);
    }
}

Methods

Push

void Push(T item)

Adds an object to the top of the Stack<T>.

Parameters:

Pop

T Pop()

Removes and returns the object at the top of the Stack<T>.

Exceptions:

Peek

T Peek()

Returns the object at the top of the Stack<T> without removing it.

Exceptions:

Clear

void Clear()

Removes all objects from the Stack<T>.

Contains

bool Contains(T item)

Determines whether an element is in the Stack<T>.

Parameters:

Returns: true if item is found in the Stack<T>; otherwise, false.

CopyTo

void CopyTo(T[] array, int arrayIndex)

Copies the entire Stack<T> to a compatible one-dimensional Array, starting at the specified index of the target array.

Parameters:

Exceptions:

Properties

Count

int get

Gets the number of elements contained in the Stack<T>.

Value: The number of elements contained in the Stack<T>.

Interfaces