Overview
The Stack<T>
class represents a last-in‑first-out (LIFO) collection of objects. It provides methods to push and pop items, as well as to peek at the top item without removing it.
public class Stack<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.Generic.IReadOnlyCollection<T>
using System; using System.Collections.Generic; class Program { static void Main() { var stack = new Stack<int>(); stack.Push(10); stack.Push(20); Console.WriteLine(stack.Peek()); // 20 Console.WriteLine(stack.Pop()); // 20 Console.WriteLine(stack.Count); // 1 } }
Type Parameters
Parameter | Description |
---|---|
T | The type of elements in the stack. |
Properties
Name | Type | Description |
---|---|---|
Count | int | Gets the number of elements contained in the Stack<T> . |
IsSynchronized | bool | Indicates whether access to the Stack<T> is synchronized (thread safe). Always false. |
SyncRoot | object | Object used to synchronize access to the Stack<T> . Always returns the current instance. |
Methods
Push
Inserts an object at the top of the Stack<T>
.
public void Push(T item)
Pop
Removes and returns the object at the top of the Stack<T>
.
public T Pop()
Peek
Returns the object at the top of the Stack<T>
without removing it.
public T Peek()
Clear
Removes all objects from the Stack<T>
.
public void Clear()
Contains
Determines whether an element is in the Stack<T>
.
public bool Contains(T item)
ToArray
Copies the Stack<T>
to a new array.
public T[] ToArray()
CopyTo
Copies the Stack<T>
to an existing one-dimensional array, starting at the specified array index.
public void CopyTo(T[] array, int arrayIndex)
GetEnumerator
Returns an enumerator that iterates through the stack.
public IEnumerator<T> GetEnumerator()
Remarks
The Stack<T>
class is sealed; therefore it cannot be inherited. It is not thread‑safe. To enable thread safety, you must synchronize access manually.