Queue class can be generic and non-generic, two different queue classes are available under System.Collections
and System.Collections.Generic
namespace. Here we learn how to work with c# Queue class with some real-time examples.
using System; using System.Collections.Generic; Queue<string> numbers = new Queue<string>(); numbers.Enqueue("India"); numbers.Enqueue("USA"); numbers.Enqueue("UK"); numbers.Enqueue("Canada");
The above example is of a generic queue, now we see non-generic queue, all methods will remain same for both generic and non-generic objects.
C# Queue is a special type of collection class which represents a first in first out concept. Queue comes under System.Collections namespace, Queue stores elements in FIFO order.
You can declare a c# queue, and create a new instance.
using System.Collections; Queue q = new Queue();
Here is code below we have created a new instance of Queue object, then added two elements in the Queue object, then retrieved them using foreach loop
So to add element we have used Enqueue method
Queue q = new Queue(); string _s = "Hello World"; int _i = 10; q.Enqueue(_s); q.Enqueue(_i); foreach (Object o in q) { Console.WriteLine(o); }
Instead of adding one element at time, we also can add an ICollection object while creating the new instance of Queue object.
Like above example we also can remove element one from Queue collection object, Dequeue()
removes and returns a first element from a queue.
If there is no element in queue then it will throw InvalidOperation exception.
Queue q = new Queue(); q.Enqueue(1); q.Enqueue(2); q.Enqueue(3); q.Enqueue(3); q.Enqueue(4); q.Dequeue(); foreach (Object o in q) { Console.WriteLine(o); }
We can retrieve values from C# using for each loop. see the below example.
Queue q = new Queue(); q.Enqueue(1); q.Enqueue(2); q.Enqueue(3); q.Enqueue(3); q.Enqueue(4); foreach (Object o in q) { Console.WriteLine(o); }
There is another method Clear()
in Queue object,
this method can be used to remove all elements from that collection.
if there is no elements still it doesn't throw any exception
Queue q = new Queue(); q.Enqueue(1); q.Enqueue(2); q.Enqueue(3); q.Enqueue(3); q.Enqueue(4); foreach (Object o in q) { Console.WriteLine(o); } // now clear all elements from collection object q.Clear();
Only when you need FIFO (first in first out) concept in your logic building, you can think of using Queue class
You should also look at others C# Data Structures Fundamental.