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 QueueSyntax
- 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 Queue class is a generic class in C#, meaning it can store objects of any type. By using generics, you can create a strongly-typed queue that only accepts a specific type of object, which enhances type safety and eliminates the need for explicit typecasting.
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.
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.