How to use C# Queue Class
The Queue class in C# is a built-in data structure that represents a first-in, first-out (FIFO) collection of objects. It is part of the System.Collections namespace and provides methods and properties for efficiently working with queues.
C# Queue class features:
- Adding Items: Items can be added to the queue using the Enqueue method. This method adds the specified object to the end of the queue, ensuring that it will be the last item to be dequeued.
- Removing Items: The Dequeue method is used to remove and return the object at the beginning of the queue. This method follows the FIFO principle, removing the item that was added first. It throws an exception if the queue is empty, so it is important to check the queue's Count property or use the TryDequeue method to safely dequeue items.
- Retrieving Items: The Peek method allows you to examine the object at the beginning of the queue without removing it. This method returns the object at the start of the queue, or throws an exception if the queue is empty.
- Counting Items: The Count property provides the number of items currently stored in the queue. This allows you to check the size of the queue and perform operations based on its count.
Important functions in the Queue Class
- Enqueue : Add an Item in Queue
- Dequeue : Remove the oldest item from Queue
- Peek : Get the reference of the oldest item
Enqueue : Add an Item in Queue
Syntax- Object : The item to add in Queue
Dequeue : Remove the oldest item from Queue (we don't get the item later)
Syntax- Returns : Remove the oldest item and return.
Peek : Get the reference of the oldest item (it is not removed permanently)
Syntax- returns : Get the reference of the oldest item in the Queue
The class Queue is a type-generic class in C# that may store objects for any type. Using generics in this approach helps you to create such a queue that can be strongly-typed, as only an object of a specified type will be able to enter the queue and not cast originally.
The Queue class in C# is typically used in scenarios where you need to process elements in the order they were added. It is commonly employed for implementing algorithms like breadth-first search, scheduling tasks, managing event queues, and more.
The following CSharp Source code shows some of commonly used functions :
Full Source C#When you execute the above C# source code , you will get Sunday in the messagebox and then it check the Monday is exist in the queue or not.
Conclusion
The Queue class in C# provides a convenient and efficient way to work with a FIFO collection of objects. It allows you to add items to the end of the queue, remove items from the beginning, retrieve items without removal, and count the number of items in the queue. It is a versatile data structure that finds application in a wide range of scenarios, where order-based processing is required.