Home » C#.Net

Queue.Clear() method with example in C#

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

C# Queue.Clear() method

Queue.Clear() method is used to remove all objects from the Queue.

Syntax:

    void Queue.Clear();

Parameters: None

Return value: void – it returns nothing.

Example:

    declare and initialize a Queue:
    Queue que = new Queue();   

    insertting elements:
    que.Enqueue(100);
    que.Enqueue(200);
    que.Enqueue(300);
    que.Enqueue(400);
    que.Enqueue(500);
    
    removing all elements:
    que.Clear();

    Output:
    None

C# example to remove all objects/elements from the Queue using Queue.Clear() method

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

namespace Test
{
    class Program
    {
        //function to print queue elements
        static void printQueue(Queue q)
        {
            foreach (Object obj in q)
            {
                Console.Write(obj + " ");
            }
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            //declare and initialize a Queue
            Queue que = new Queue();

            //insertting elements
            que.Enqueue(100);
            que.Enqueue(200);
            que.Enqueue(300);
            que.Enqueue(400);
            que.Enqueue(500);

            //printing length
            Console.WriteLine("Total elements: " + que.Count);

            //printing queue elements
            Console.WriteLine("Queue elements are...");
            printQueue(que);

            //removing all elements
            que.Clear();

            //printing length
            Console.WriteLine("After Clear(), total elements: " + que.Count);

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

Output

Total elements: 5
Queue elements are...
100 200 300 400 500
After Clear(), total elements: 0

Reference: Queue.Clear Method



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.