The Queue class in C# is the first-in, first-out collection of objects. Let us see some of the methods of the Queue class in C# −
| Sr.No | Methods & Description |
|---|---|
| 1 | Clear() Removes all objects from the Queue<T>. |
| 2 | Contains(T) Determines whether an element is in the Queue<T>. |
| 3 | CopyTo(T[], Int32) Copies the Queue>T< elements to an existing onedimensional Array, starting at the specified array index. |
| 4 | Dequeue() Removes and returns the object at the beginning of the Queue<T>. |
| 5 | Enqueue(T) Adds an object to the end of the Queue<T>. |
| 6 | Equals(Object) Determines whether the specified object is equal to the current object.(Inherited from Object) |
| 7 | GetEnumerator() Returns an enumerator that iterates through the Queue<T> |
| 8 | GetHashCode() Serves as the default hash function. (Inherited from Object) |
| 9 | GetType() Gets the Type of the current instance. |
Example
Let us now see some examples −
To get the object at the beginning of the Queue, the code is as follows −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Queue<string> queue = new Queue<string>();
queue.Enqueue("A");
queue.Enqueue("B");
queue.Enqueue("C");
queue.Enqueue("D");
queue.Enqueue("E");
queue.Enqueue("F");
queue.Enqueue("G");
Console.WriteLine("Count of elements = "+queue.Count);
Console.WriteLine("Element at the beginning of queue = " + queue.Peek());
}
}Output
This will produce the following output −
Count of elements = 7 Element at the beginning of queue = A
To remove all objects from the Queue, the code is as follows −
Example
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Queue<string> queue = new Queue<string>();
queue.Enqueue("Gary");
queue.Enqueue("Jack");
queue.Enqueue("Ryan");
queue.Enqueue("Kevin");
queue.Enqueue("Mark");
queue.Enqueue("Jack");
queue.Enqueue("Ryan");
queue.Enqueue("Kevin");
Console.Write("Count of elements = ");
Console.WriteLine(queue.Count);
queue.Clear();
Console.Write("Count of elements (updated) = ");
Console.WriteLine(queue.Count);
}
}Output
This will produce the following output −
Count of elements = 8 Count of elements (updated) = 0