Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
How to create a Queue in C#
Next article icon

C# Queue Class

Last Updated : 31 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C#, the Queue<T> class is the part of the System.Collections.Generic namespace and represent a first-in-first-out (FIFO) collection of objects. When we add an item to the list, it is called enqueue, and when we remove an item, it is called dequeue.

  • Enqueue adds an element to the end of the Queue.
  • Dequeue removes the oldest element from the start of the Queue.
  • Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue.
  • The capacity of a Queue is the number of elements the Queue can hold.
  • As elements are added to a Queue, the capacity is automatically increased as required by reallocating the internal array.
  • Queue accepts null as a valid value for reference types and allows duplicate elements.

Example: This example, demonstrates how to create a queue, add different elements to it using the enqueue() Method, and then display the elements using for-each loop.

C#
// C# program to demonstrates the working of queue using System; using System.Collections;  public class Geeks {     static public void Main()     {          // Create a queue         // Using Queue class         Queue q = new Queue();          // Adding elements in Queue         // Using Enqueue() method         q.Enqueue("GFG");         q.Enqueue(1);         q.Enqueue(10);         q.Enqueue(null);         q.Enqueue(2.4);         q.Enqueue("Geeks123");          // Accessing the elements         // of q Queue         // Using foreach loop         foreach(var i in q) {            Console.WriteLine(i);          }     } } 

Output
GFG 1 10  2.4 Geeks123 

Declaration of Queue Class

In C#, the Queue<T> is a generic collection, meaning it can hold elements of a specific type. T is the type of elements the queue will hold

Queue<T> q = new Queue<T>();

Constructors

The Queue<T> class provides four constructor which are listed below in the table:

Constructor

Description

Queue()

Initializes a new instance of the Queue class that is empty, has the default initial capacity, and uses the default growth factor.

Queue(ICollection)

Initializes a new instance of the Queue class that contains elements copied from the specified collection, has the same initial capacity as the number of elements copied, and uses the default growth factor.

Queue(Int32)

Initializes a new instance of the Queue class that is empty, has the specified initial capacity, and uses the default growth factor.

Queue(Int32,Single)

 Initializes a new instance of the Queue class that is empty, has the specified initial capacity, and uses the specified growth factor

Example: This example demonstrates the total number of elements present in the queue.

C#
// C# program to count the number  // of elements present in the queue using System; using System.Collections;  class Geeks {      public static void Main()     {          // Creating a Queue         Queue q = new Queue();          // Inserting the elements into the Queue         q.Enqueue("one");         q.Enqueue("two");         q.Enqueue("three");         q.Enqueue("four");         q.Enqueue("five");          // Displaying the count of elements         // contained in the Queue         Console.Write(             "Total number of elements in the Queue are : ");          Console.WriteLine(q.Count);     } } 

Output
Total number of elements in the Queue are : 5 

Properties

The Queue<T> class provides several properties to access its state.

PropertyDescription
CountGets the number of elements contained in the Queue.
IsSynchronizedGets a value indicating whether access to the Queue is synchronized (thread safe).
SyncRootGets an object that can be used to synchronize access to the Queue.

Example: This example demonstrates how to use the SyncRoot property of a Queue to ensure thread safety.

C#
// C# program to illustrate the // use of SyncRoot property of // the Queue using System; using System.Threading; using System.Collections;  namespace sync_root {  class Geeks {      // Main Method     static void Main(string[] args)     {          // Declaring an Queue         Queue q = new Queue();          // Adding elements to Queue         q.Enqueue(1);         q.Enqueue(2);         q.Enqueue(3);         q.Enqueue(4);         q.Enqueue(5);          // Using the SyncRoot property         lock(q.SyncRoot)         {             // foreach loop to display             // the elements in q1             foreach(Object i in q) Console.WriteLine(i);         }     } } } 

Output
1 2 3 4 5 

Methods

MethodDescription
Clear()Removes all objects from the Queue.
Clone()Creates a shallow copy of the Queue.
Contains(Object)Determines whether an element is in the Queue.
CopyTo(Array, Int32)Copies the Queue elements to an existing one-dimensional Array, starting at the specified array index.
Dequeue()Removes and returns the object at the beginning of the Queue.
Enqueue(Object)Adds an object to the end of the Queue.
Equals(Object)Determines whether the specified object is equal to the current object.
GetEnumerator()Returns an enumerator that iterates through the Queue.
GetHashCode()Serves as the default hash function.
GetType()Gets the Type of the current instance.
MemberwiseClone()Creates a shallow copy of the current Object.
Peek()Returns the object at the beginning of the Queue without removing it.
Synchronized(Queue)Returns a new Queue that wraps the original queue, and is thread safe.
ToArray()Copies the Queue elements to a new array.
ToString()Returns a string that represents the current object.
TrimToSize()Sets the capacity to the actual number of elements in the Queue.

Example: This example demonstrates that the specific element is present in the Queue using the Contains() method.

C#
// C# Program to check if the specified  // element is present in the queue or not  using System; using System.Collections;  class Geeks {      public static void Main()     {          // Creating a Queue         Queue q = new Queue();          // Inserting the elements into the Queue         q.Enqueue(5);         q.Enqueue(10);         q.Enqueue(15);         q.Enqueue(20);         q.Enqueue(25);          // Checking whether the element is         // present in the Queue or not         Console.WriteLine("The queue contains 7 ? :"                           + q.Contains(7));         Console.WriteLine("The queue contains 10 ? :"                           + q.Contains(10));     } } 

Output
The queue contains 7 ? :False The queue contains 10 ? :True 

Example: This example demonstrates how to convert a Queue to an object array using ToArray() method.

C#
// C# Program to Convert Queue to array using System; using System.Collections;  class Geeks {      public static void Main()     {          // Creating a Queue           Queue q = new Queue();          // Inserting the elements into the Queue          q.Enqueue("Geeks");         q.Enqueue("for");         q.Enqueue("Geeks");          // Converting the Queue          // into object array          Object[] arr = q.ToArray();          // Displaying the elements in array          foreach(Object i in arr)         {             Console.WriteLine(i);         }     } } 

Output
Geeks for Geeks 


Next Article
How to create a Queue in C#

S

Sahil_Bansall
Improve
Article Tags :
  • C#
  • CSharp-Collections-Namespace
  • CSharp-Queue-Class

Similar Reads

  • C# Queue Class
    In C#, the Queue<T> class is the part of the System.Collections.Generic namespace and represent a first-in-first-out (FIFO) collection of objects. When we add an item to the list, it is called enqueue, and when we remove an item, it is called dequeue. Enqueue adds an element to the end of the
    5 min read
  • How to create a Queue in C#
    Queue() Constructor is used to initializes a new instance of the Queue class which will be empty, and will have the default initial capacity, and uses the default growth factor. Queue represents a first-in, first out collection of object. It is used when you need first-in, first-out access of items.
    2 min read
  • Queue.Count Property in C#
    This property is used to get the number of elements contained in the Queue. Retrieving the value of this property is an O(1) operation and it comes under the System.Collections namespace. Syntax: public virtual int Count { get; } Property Value: This property returns the number of elements contained
    2 min read
  • Queue.IsSynchronized Property in C#
    This property is used get a value which indicates whether access to the Queue is synchronized (thread safe) or not. Syntax: public virtual bool IsSynchronized { get; } Property Value: This property returns true if access to the Queue is synchronized(thread safe) otherwise, false. The default is fals
    2 min read
  • How to get Synchronize access to the Queue in C#
    Queue.SyncRoot Property is used to get an object which can be used to synchronize access to the Queue. Queue represents a first-in, first out collection of object. It is used when you need first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remov
    2 min read
  • Queue.Clear Method in C#
    This method is used to remove the objects from the Queue. This method is an O(n) operation, where n is the total count of elements. And this method comes under System.Collections namespace. Syntax: public void Clear (); Below given are some examples to understand the implementation in a better way:
    2 min read
  • Queue.Clone() Method in C#
    This method is used to create a shallow copy of the Queue. It just creates a copy of the Queue. The copy will have a reference to a clone of the internal elements but not a reference to the original elements. Syntax: public virtual object Clone (); Return Value: The method returns an Object which is
    2 min read
  • Queue.Contains() Method in C#
    This method is used to check whether an element is in the Queue. This method performs a linear search, therefore, this method is an O(n) operation, where n is Count. And this method comes under the System.Collections namespace. Syntax: public virtual bool Contains(object obj); Here, obj is the Objec
    2 min read
  • Queue.CopyTo() Method in C#
    This method is used to copy the Queue elements to an existing one-dimensional Array, starting at the specified array index. The elements are copied to the Array in the same order in which the enumerator iterates through the Queue and this method is an O(n) operation, where n is Count. This method co
    4 min read
  • Queue.Dequeue Method in C#
    The Dequeue() method is used to returns the object at the beginning of the Queue. This method is similar to the Peek() Method. The only difference between Dequeue and Peek method is that Peek() method will not modify the Queue but Dequeue will modify. This method is an O(1) operation and comes under
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences