web training room for online courses
Learn C# programming Language, Free C# Tutorial for Beginners, C# Development Guide

Queue Class in C# Example

What is Queue Class in C# Programming?

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.

Queue Declaration
using System.Collections;
Queue q = new Queue();
Adding new element to Queue object

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.

Dequeue: Removing element from Queue collection 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);
}
Queue Clear Method

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();
Important Queue Functions and Methods
  • Enqueue
    adding new element to Queue, specifically at the end of the queue
  • Dequeue
    removes and returns a first element from a queue
  • Clear
    clear all elements from queue collection object
  • Peek
    Return the at the beginning of queue
  • Contains
    Determine if the queue has a particular element or not, returns boolean property
  • Count
    a property, that returns a number, get the number of items in the Queue
When to use Queue class in C# programming?

Only when you need FIFO (first in first out) concept in your logic building, you can think of using Queue class

Comment
Name Email Website
Subscribe
 
Queue in C# Example
Learn C# Online Tutorial


Consulting