Queue<T> is similar to Stack<T>. Difference is that Queue <T> is based on FIFO principle. First in first out. Meaning  element will be added to first location in the collection and when we try to remove element from the collection first element will be removed.

Declaration

Queue<T> can can contain reference or value types. We declare a Queue<T> by typing Queue followed by<> (angle brackets) and inside <> should be our type and after that should be variable name:

 

Initialization

As Queue<T>  is an reference type so we initialize it by assigning Queue variable to Queue instance. Queue<T> type should be specified while instantiating Queue<T>.

Populating a Queue<T> with values using Enqueue method

Queue<T> is populated by using Enqueue method.

Remove an element from the Queue <T>

Dequeue element

By using Dequeue method we can remove first element of the Queue<T> and get that value.

By using Dequeue method value will be removed from the Queue<T> and Count property will be decremented by 1.

Clear Queue <T>

By using Clear method all Queue<T> elements will be removed from the Queue<T>.

How to use Queue <T>

Peek first value

By using Peek method we can inspect first value with no fear of dequeuing it from the Queue.

Iterate through Queue<T>

We can iterate an Queue<T> using for and foraech statements. Using these loops elements will not be dequeued from the Queue<T>.

 

 

Number of elements inside of a Queue<T>