Queue in c# with example

Queue in c# with example


Queue in C# with Example

In C#, the Queue<T> class is a part of the System.Collections.Generic namespace and represents a first-in, first-out (FIFO) collection of objects. This article provides an overview of the Queue<T> class, detailing how to use its various methods to manage a queue efficiently in various applications.

Understanding the Queue<T> Class

The Queue<T> class provides operations for enqueueing (adding), dequeueing (removing), and peeking (viewing the next item) in a queue. It is a generic collection that ensures type safety by allowing only objects of a specified type to be added, eliminating the need for type casting and reducing runtime errors.

Key Features of Queue<T>

  • FIFO Order: Items are removed from the collection in the order they were added.
  • Dynamic Capacity: The capacity of the queue increases automatically as elements are added.
  • Type Safety: Being a part of generic collections, it ensures that all elements are of the same specified type.

Common Methods of Queue<T>

  • Enqueue(T item): Adds an item to the end of the queue.
  • Dequeue(): Removes and returns the item at the beginning of the queue.
  • Peek(): Returns the item at the beginning of the queue without removing it.
  • Count: Gets the number of elements contained in the queue.

Example: Using Queue<T> in C#

Here’s a simple example demonstrating the creation and operation of a Queue<T>:

 

Queue<string> queue = new Queue<string>();

// Enqueueing items
queue.Enqueue("Apple");
queue.Enqueue("Banana");
queue.Enqueue("Cherry");

// Peeking at the first item
Console.WriteLine("First item: " + queue.Peek());  // Outputs: Apple

// Dequeueing items
while (queue.Count > 0)
{
    string fruit = queue.Dequeue();
    Console.WriteLine("Removed: " + fruit);
}

This example shows how items are added to and removed from the queue. The Peek method is used to look at the first item without removing it from the queue, which is useful for scenarios where you need to inspect the next item to be processed but do not yet want to remove it.

Use Cases for Queue<T>

  • Task Scheduling: Managing tasks in multi-threading environments where tasks must be executed in the order they were added.
  • Resource Sharing: Managing access to shared resources in computing environments, such as printer queues.
  • Data Processing: In scenarios where data must be processed in the same order it was received, such as network packet processing.

Conclusion

The Queue<T> class in C# is a powerful tool for managing collections that need to operate in a FIFO manner. By understanding how to utilize the Queue<T> effectively, developers can implement robust data structures tailored for various applications requiring orderly processing of items.


 

Leave a reply Your email address will not be published. Required fields are marked*