SoFunction
Updated on 2025-03-06

C# built-in queue class Queue usage example

This article describes the usage of the C# built-in queue class Queue. Share it for your reference. The specific analysis is as follows:

Here we demonstrate in detail how to add, remove and other functions built-in queues in C#.

using System;
using ;
class Example
{
 public static void Main()
 {
  Queue<string> numbers = new Queue<string>();
  ("one");
  ("two");
  ("three");
  ("four");
  ("five");
  // A queue can be enumerated without disturbing its contents.
  foreach( string number in numbers )
  {
   (number);
  }
  ("\nDequeuing '{0}'", ());
  ("Peek at next item to dequeue: {0}", 
   ());
  ("Dequeuing '{0}'", ());
  // Create a copy of the queue, using the ToArray method and the
  // constructor that accepts an IEnumerable<T>.
  Queue<string> queueCopy = new Queue<string>(());
  ("\nContents of the first copy:");
  foreach( string number in queueCopy )
  {
   (number);
  }
  // Create an array twice the size of the queue and copy the
  // elements of the queue, starting at the middle of the 
  // array. 
  string[] array2 = new string[ * 2];
  (array2, );
  // Create a second queue, using the constructor that accepts an
  // IEnumerable(Of T).
  Queue<string> queueCopy2 = new Queue<string>(array2);
  ("\nContents of the second copy, with duplicates and nulls:");
  foreach( string number in queueCopy2 )
  {
   (number);
  }
  ("\(\"four\") = {0}", 
   ("four"));
  ("\()");
  ();
  ("\ = {0}", );
 }
}
/* This code example produces the following output:
one
two
three
four
five
Dequeuing 'one'
Peek at next item to dequeue: two
Dequeuing 'two'
Contents of the copy:
three
four
five
Contents of the second copy, with duplicates and nulls:
three
four
five
("four") = True
()
 = 0
 */

I hope this article will be helpful to everyone's C# programming.