How to use Queue class in C#?


Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access to items. When you add an item to the list, it is called enqueue, and when you remove an item, it is called deque.

The following table lists some of the commonly used methods of the Queue class −

Sr.NoMethod & Description
1public virtual void Clear();
Removes all elements from the Queue.
2public virtual bool Contains(object obj);
Determines whether an element is in the Queue.
3public virtual object Dequeue();
Removes and returns the object at the beginning of the Queue.
4public virtual void Enqueue(object obj);
Adds an object to the end of the Queue.
5public virtual object[] ToArray();
Copies the Queue to a new array.

Let us see an example of the Queue class −

Example

 Live Demo

using System;
using System.Collections;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         Queue q = new Queue();

         q.Enqueue('X');
         q.Enqueue('Y');
         q.Enqueue('Z');
   
         Console.WriteLine("Current queue: ");
         foreach (char c in q) Console.Write(c + " ");

         Console.WriteLine();
         q.Enqueue('A');
   
         Console.WriteLine("Current queue: ");
         foreach (char c in q) Console.Write(c + " ");

         Console.WriteLine();
         Console.ReadKey();
      }
   }
}

Output

Current queue:
X Y Z
Current queue:
X Y Z A

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Jun-2020

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements