Rahees Ahmed
Rahees Ahmed

Reputation: 23

How to Pop all element in Stack using function

Hi i want to empty the full Stack by function not one by one i want to use a loop in a function which delete/Pop all the stack element you can see my code

using System;
using System.Collections;
public class SamplesStack
{

    public static void Main()
    {

        // Creates and initializes a new Stack.
        Stack myStack = new Stack();
        myStack.Push("Hello");
        myStack.Push("World");
        myStack.Push("!");


        // Displays the properties and values of the Stack.
       // Console.WriteLine("myStack");
        Console.WriteLine("\tCount:    {0}", myStack.Count);
        Console.Write("\tValues:");
        PrintValues(myStack);
       object pt = myStack.Pop();
        Console.WriteLine("\tCount:    {0}", myStack.Count);
        Console.ReadLine();
    }

    public static void PrintValues(IEnumerable myCollection)
    {
        foreach (Object obj in myCollection)
            Console.Write("    {0}", obj);
        Console.WriteLine();
    }
    public static void emptyStack(Stack empty)
    {
     what to do here

    }

Upvotes: 1

Views: 2310

Answers (2)

Rahees Ahmed
Rahees Ahmed

Reputation: 23

So here is the answer to my Question i have tried different Things so i have done this by this function

public static void PopStack(Stack stObj)
    {
        foreach (var st in stObj.ToArray())
        {
            var obj= stObj.Pop();
            Console.WriteLine(count);
            Console.WriteLine(obj);

        }

        Console.WriteLine("\tCount:    {0}", stObj.Count);

    }

Upvotes: 0

dvo
dvo

Reputation: 2153

You have a few different options. Here are a couple:

  1. The easy option is one line of code mentioned in the comments: myStack.Clear(); (Microsoft Doc).
  2. Loop through the stack and pop until it's empty:
while(myStack.Count > 0) 
{ 
   myStack.Pop();
}

Upvotes: 1

Related Questions