Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
queue
clear
communitycreator

How to remove all elements of a queue in C#

Surabhi Sharma

The Queue<T> generic class in the System.Collections.Generic namespace provides the Clear() method, which can be used to remove all objects from the queue. The queue becomes empty after the Clear() method is called.

Syntax

public void Clear ();
  • The C# queue is maintained as a circular array and the Clear() method internally calls the Array.Clear() method to empty the queue.
  • The Queue Count property becomes 0zero after the Clear() method is called.
  • This method changes the state of the queue.
Empty a Queue using Clear() method

In the example below, we created a queue of strings to store month names and added the first six months to it.

After we added the elements, we printed all the elements present in the queue.

The Clear() method was called on the queue object, and it emptied the queue.

After this, we again printed the queue elements, and we can now observe that the queue is empty.

using System;
using System.Collections.Generic;

class QueueRemover
{
    static void Main()
    {
        Queue<string> months = new Queue<string>();
        months.Enqueue("January");
        months.Enqueue("February");
        months.Enqueue("March");
        months.Enqueue("April");
        months.Enqueue("May");
        months.Enqueue("June");

        Console.WriteLine("Queue Items Before Clear() : {0}", string.Join(",", months.ToArray()));
        months.Clear();
        Console.WriteLine("Queue Items After Clear() : {0}", string.Join(",", months.ToArray()));


    }
}
Empty a Queue with the Clear() method

RELATED TAGS

c#
queue
clear
communitycreator
RELATED COURSES

View all Courses

Keep Exploring