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.
public void Clear ();
Clear()
method internally calls the Array.Clear()
method to empty the queue.Clear()
method is called.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()));}}