Queue.Clone() Method in C#


The Queue.Clone() method in C# is used to create a shallow copy of the Queue.

Syntax

The syntax is as follows -

public virtual object Clone ();

Example

Let us now see an example -

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(string[] args) {
      Queue queue = new Queue();
      queue.Enqueue("One");
      queue.Enqueue("Two");
      queue.Enqueue("Three");
      queue.Enqueue("Four");
      queue.Enqueue("Five");
      queue.Enqueue("Six");
      queue.Enqueue("Seven");
      queue.Enqueue("Eight");
      Console.WriteLine("Queue...");
      foreach(string str in queue) {
         Console.WriteLine(str);
      }
      Queue queue2 = (Queue)queue.Clone();
      Console.WriteLine("\nCloned Queue....");
      foreach(string str in queue2) {
         Console.WriteLine(str);
      }
   }
}

Output

Queue...
One
Two
Three
Four
Five
Six
Seven
Eight
Cloned Queue....
One
Two
Three
Four
Five
Six
Seven
Eight

Example

Let us now see another example -

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(string[] args) {
      Queue queue = new Queue();
      queue.Enqueue(10);
      queue.Enqueue(20);
      queue.Enqueue(30);
      queue.Enqueue(40);
      queue.Enqueue(50);
      Console.WriteLine("Queue...");
      foreach(int str in queue) {
         Console.WriteLine(str);
      }
      Queue queue2 = (Queue)queue.Clone();
      Console.WriteLine("\nCloned Queue....");
      foreach(int str in queue2) {
         Console.WriteLine(str);
      }
   }
}

Output

This will produce the following output -

Queue...
10
20
30
40
50
Cloned Queue....
10
20
30
40
50
raja
Published on 03-Dec-2019 13:04:27
Advertisements