Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
stack
clear
communitycreator

How to remove all elements from a stack in C#

Surabhi Sharma

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()));
    }
}

RELATED TAGS

c#
stack
clear
communitycreator
RELATED COURSES

View all Courses

Keep Exploring