How to remove all elements from a stack in C#

The Stack<T> generic class in the System.Collections.Generic namespace provides the Clear() method, which can be used to remove all the elements of a stack in C#.

Syntax

public void Clear ();

Things to note

  • Other object references from elements of Stack<T> are also released after the Clear() method is called.

  • The stack’s Count property becomes 0 after the Clear() method is called.

  • This method does not change the capacity of the stack.

  • This method changes the state of the stack.

  • This is an O(n) operation, where nn is the count of elements.

Removing all stack elements using Clear() method

Code

In the following code, we create a stack of strings.

First, we call the Push() method with the strings Asia, Africa, and Europe. This inserts these three strings onto the stack, with Europe at the top of the stack.

We display all the stack elements, and we can see that it has three elements in it.

We then call the Clear() method and print the count of the stack. We also display all elements of the stack. As we can observe in the output, the stack does not have any elements, and count is set to zero.

using System;
using System.Collections.Generic;
class StackClear
{
static void Main()
{
Stack<string> stack = new Stack<string>();
stack.Push("Asia");
stack.Push("Africa");
stack.Push("Europe");
Console.WriteLine("Current Stack Items: \n{0}\n", string.Join(",", stack.ToArray()));
stack.Clear();
Console.WriteLine("Stack Count Ater Clear(): {0}", stack.Count);
Console.WriteLine("Stack Items After Clear():\n{0}", string.Join(",", stack.ToArray()));
}
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources