Home » C#.Net

Stack.Clear() method with example in C#

C# Stack.Clear() method: Here, we are going to learn about the Clear() method of Stack class in C#.
Submitted by IncludeHelp, on March 28, 2019

C# Stack.Clear() method

Stack.Peek() method is used to remove all objects from the stack.

Syntax:

    void Stack.Clear();

Parameters: None

Return value: void – it returns nothing.

Example:

    declare and initialize a stack:
    Stack stk = new Stack();

    insertting elements:
    stk.Push(100);
    stk.Push(200);
    stk.Push(300);
    stk.Push(400);
    stk.Push(500);

    clearing all objects/elements:
    stk.Clear();
    
    Output:
    None

C# example to clear all objects from the stack using Stack.Clear() method

using System;
using System.Text;
using System.Collections;

namespace Test
{
    class Program
    {
        //function to print stack elements
        static void printStack(Stack s)
        {
            foreach (Object obj in s)
            {
                Console.Write(obj + " ");
            }
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            //declare and initialize a stack
            Stack stk = new Stack();

            //insertting elements
            stk.Push(100);
            stk.Push(200);
            stk.Push(300);
            stk.Push(400);
            stk.Push(500);

            Console.WriteLine("Total number of objects in the stack: " + stk.Count);

            //printing stack elements
            Console.WriteLine("Stack elements are...");
            printStack(stk);

            //clearing all objects/elements
            stk.Clear();

            Console.WriteLine("Total number of objects in the stack: " + stk.Count);


            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

Total number of objects in the stack: 5
Stack elements are...
500 400 300 200 100
Total number of objects in the stack: 0

Reference: Stack.Clear Method

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.