C Sharp Queue

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# Queue<T>

C# Queue class is used to Enqueue and Dequeue elements. It uses the concept of Queue that arranges elements in FIFO (First In First Out) order. It can have duplicate elements. It is found in System.Collections.Generic namespace.

C# Queue<T> example

Let's see an example of generic Queue class that stores elements using Enqueue() method, removes elements using Dequeue() method and iterates elements using for-each loop.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. public class QueueExample  
  5. {  
  6.     public static void Main(string[] args)  
  7.     {  
  8.         Queue<string> names = new Queue<string>();  
  9.         names.Enqueue("Sonoo");  
  10.         names.Enqueue("Peter");  
  11.         names.Enqueue("James");  
  12.         names.Enqueue("Ratan");  
  13.         names.Enqueue("Irfan");  
  14.   
  15.         foreach (string name in names)  
  16.         {  
  17.             Console.WriteLine(name);  
  18.         }  
  19.   
  20.         Console.WriteLine("Peek element: "+names.Peek());  
  21.         Console.WriteLine("Dequeue: "+ names.Dequeue());  
  22.         Console.WriteLine("After Dequeue, Peek element: " + names.Peek());  
  23.     }  
  24. }  

Output:

Sonoo
Peter
James
Ratan
Irfan
Peek element: Sonoo
Dequeue: Sonoo
After Dequeue, Peek element: Peter