System.Collections.Generic.Stack<T> Class
Represents a collection of objects that can be accessed by index. Thelastobject added to theStackis thefirstone that is removed.
Table of Contents
Constructors
-
public Stack<T>()
Initializes a new instance of the
Stack<T>
class that is empty, has the default initial capacity, and uses the reference equality comparer for the list type. -
public Stack<T>(int capacity)
Initializes a new instance of the
Stack<T>
class that is empty, has the specified initial capacity, and uses the reference equality comparer for the list type.Parameters:
capacity
: The number of elements that the new stack can initially hold.
Properties
-
public int Count { get; }
Gets the number of elements contained in the
Stack<T>
.
Methods
-
public void Push(T item)
Inserts an item at the top of the
Stack<T>
.Parameters:
item
: The item to push onto theStack<T>
. The value can be null for reference types.
-
public T Pop()
Removes and returns the object at the top of the
Stack<T>
.Returns:
The object removed from the top of the
Stack<T>
.Exceptions:
InvalidOperationException
: TheStack<T>
is empty.
-
public T Peek()
Returns the object at the top of the
Stack<T>
without removing it.Returns:
The object at the top of the
Stack<T>
.Exceptions:
InvalidOperationException
: TheStack<T>
is empty.
-
public bool Contains(T item)
Determines whether an element is in the
Stack<T>
.Parameters:
item
: The item to locate in theStack<T>
. The value can be null for reference types.
Returns:
true
if item is found in theStack<T>
; otherwise,false
. -
public void Clear()
Removes all objects from the
Stack<T>
.
Examples
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 } }