The Stack<T>.Pop() method in C# removes and returns the element that was added most recently. Since a stack follows the Last-In, First-Out (LIFO) principle, Pop() removes the next element in LIFO order.
- It returns and removes an element from the stack.
- The Count of the stack decreases by one after a successful Pop() operation.
using System;
using System.Collections.Generic;
class GFG{
public static void Main(){
Stack<string> myStack = new Stack<string>();
myStack.Push("One");
myStack.Push("Two");
myStack.Push("Three");
myStack.Push("Four");
Console.WriteLine("Number of elements: " + myStack.Count);
string removedElement = myStack.Pop();
Console.WriteLine("Removed element: " + removedElement);
Console.WriteLine("Number of elements after Pop(): "
+ myStack.Count);
}
}
Output
Number of elements: 4 Removed element: Four Number of elements after Pop(): 3
Explanation: "Four" was the most recently added element, so Pop() returns and removes it. As a result, the number of elements decreases from 4 to 3.
Syntax
public T Pop();
- Return Value: The Pop() method returns the element of type T that is removed from the Stack<T>.
- Exception: Pop() throws an InvalidOperationException if the stack is empty. Therefore, check the Count property before calling Pop() when the stack may be empty.
How Pop() Works
Suppose a stack contains the following elements:
three <- Next to be removed
two
one
Calling:
myStack.Pop();
removes and returns "three". The stack then becomes:
two
one
Pop() on an Empty Stack
Calling Pop() on an empty stack throws an InvalidOperationException.
Stack<int> myStack = new Stack<int>();
Console.WriteLine(myStack.Pop());
Runtime Error:
System.InvalidOperationException: Stack empty.
To avoid this exception:
if (myStack.Count > 0){
Console.WriteLine(myStack.Pop());
}
else
{
Console.WriteLine("Stack is empty.");
}
Pop() vs Peek()
| Pop() | Peek() |
|---|---|
| Returns an element | Returns an element |
| Removes the returned element | Does not remove the returned element |
| Decreases Count by one | Count remains unchanged |
| Time complexity is O(1) | Time complexity is O(1) |
| Throws InvalidOperationException if empty | Throws InvalidOperationException if empty |