C# Queue<T> class is employed to add elements to the queue and remove them in a specific order. This class follows the FIFO (First In First Out) principle for organizing elements. It supports the inclusion of duplicate elements and is located within the System.Collections.Generic namespace.
C# Queue__PRESERVE_4__ example
Let's examine an instance of a generic Queue<T> class that stores items via the Enqueue function, deletes items through the Dequeue operation, and cycles through elements using a for-each loop.
Example
using System;
using System.Collections.Generic;
public class QueueExample
{
public static void Main(string[] args)
{
Queue<string> names = new Queue<string>();
names.Enqueue("Sonoo");
names.Enqueue("Peter");
names.Enqueue("James");
names.Enqueue("Ratan");
names.Enqueue("Irfan");
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("Peek element: "+names.Peek());
Console.WriteLine("Dequeue: "+ names.Dequeue());
Console.WriteLine("After Dequeue, Peek element: " + names.Peek());
}
}
Output:
Output
Sonoo
Peter
James
Ratan
Irfan
Peek element: Sonoo
Dequeue: Sonoo
After Dequeue, Peek element: Peter