Adding Elements to a C# Queue: Using the `Queue.Enqueue()` Method

Learn how to efficiently add elements to a queue in C# using the `Queue.Enqueue()` method. This tutorial covers its functionality, time complexity, and best practices for managing FIFO (First-In, First-Out) data structures, illustrating its use in various programming scenarios.



Adding Elements to a Queue in C#: The `Queue.Enqueue()` Method

Introduction

In C#, the `Queue.Enqueue()` method adds an element to the end of a queue data structure. Queues follow the FIFO (First-In, First-Out) principle: the first item added is the first item removed.

`Queue.Enqueue()` Method Details

The `Enqueue()` method is part of the `Queue` class (in `System.Collections.Generic`). It takes the element you want to add as an argument. The time complexity is typically O(1) (constant time), unless the internal array needs to be resized to accommodate the new element, in which case it becomes O(n), where n is the number of elements.

Method Syntax

`Queue.Enqueue()` Syntax

public void Enqueue(T item);

Parameter

item: The object to add to the end of the queue.

Example: Adding Elements to a Queue

`Queue.Enqueue()` Example

using System;
using System.Collections.Generic;

class EnqueueExample {
    static void Main(string[] args) {
        Queue<string> myQueue = new Queue<string>();
        myQueue.Enqueue("one");
        Console.WriteLine($"Count: {myQueue.Count}"); // Output: 1
        myQueue.Enqueue("two");
        Console.WriteLine($"Count: {myQueue.Count}"); // Output: 2
        // ... add more elements ...
    }
}

Advantages of Using `Queue.Enqueue()`

  • FIFO Ordering: Maintains the order of elements.
  • Efficient Addition: Typically O(1) time complexity.
  • Dynamic Resizing: Handles varying numbers of elements automatically.
  • Thread Safety: The `Queue` class is thread-safe, making it suitable for multithreaded environments.
  • Simple API: Easy to use and understand.

Conclusion

The `Queue.Enqueue()` method is a fundamental part of working with queues in C#. Its efficiency and built-in thread safety make it a valuable tool for managing ordered collections of data.