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.
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.
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);
}
}
void Push(T item)
Adds an object to the top of the Stack<T>.
Parameters:
item
: The object to add to the top of the Stack<T>. The value can be null for reference types.T Pop()
Removes and returns the object at the top of the Stack<T>.
Exceptions:
T Peek()
Returns the object at the top of the Stack<T> without removing it.
Exceptions:
void Clear()
Removes all objects from the Stack<T>.
bool Contains(T item)
Determines whether an element is in the Stack<T>.
Parameters:
item
: The object to locate in the Stack<T>. The value can be null for reference types.Returns: true if item is found in the Stack<T>; otherwise, false.
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:
array
: The one-dimensional Array that is the destination of the elements copied from the Stack<T>. The Array must have zero-based indexing.arrayIndex
: The zero-based index in array at which copying begins.Exceptions:
int get
Gets the number of elements contained in the Stack<T>.
Value: The number of elements contained in the Stack<T>.