What is Queue in C#: Definition, Usage, and Examples
Queue is a collection that stores items in a first-in, first-out (FIFO) order. It means the first item added is the first one to be removed, similar to a line of people waiting their turn. The Queue class provides methods to add, remove, and peek at items efficiently.How It Works
A Queue in C# works like a real-life queue or line, such as people waiting at a ticket counter. The first person to get in line is the first person to be served and leave the line. This is called FIFO (First In, First Out).
When you add an item to a Queue, it goes to the back of the line. When you remove an item, it comes from the front. This way, the order of items is always kept.
The Queue class in C# provides simple methods like Enqueue to add items, Dequeue to remove the front item, and Peek to look at the front item without removing it.
Example
This example shows how to create a Queue, add items, remove an item, and check the front item.
using System; using System.Collections.Generic; class Program { static void Main() { Queue<string> line = new Queue<string>(); // Add people to the queue line.Enqueue("Alice"); line.Enqueue("Bob"); line.Enqueue("Charlie"); // Show the person at the front Console.WriteLine("First in line: " + line.Peek()); // Serve the first person string served = line.Dequeue(); Console.WriteLine("Served: " + served); // Show the new front Console.WriteLine("Next in line: " + line.Peek()); } }
When to Use
Use a Queue when you need to process items in the order they arrive, like customers waiting in line or tasks waiting to be done. It is perfect for scenarios where order matters and you want to handle things fairly.
Common uses include:
- Printing jobs sent to a printer
- Handling requests in a web server
- Processing tasks in the order they were added
Key Points
- FIFO order: First item added is first removed.
- Enqueue: Adds an item to the back.
- Dequeue: Removes the front item.
- Peek: Views the front item without removing.
- Useful for: Managing ordered tasks or requests.