Queue.Clone() Method in C#

This method is used to create a shallow copy of the Queue. It just creates a copy of the Queue. The copy will have a reference to a clone of the internal elements but not a reference to the original elements.

Syntax: public virtual object Clone ();

Return Value: The method returns an Object which is just the shallow copy of the Queue.

Example 1: Let’s see an example without using a Clone() method and directly copying a Queue using assignment operator ‘=’. In the below code, we can see even if we Dequeue() elements from myQueue2, contents of myQueue is also changed. This is because ‘=’ just assigns the reference of myQueue to myQueue2 and does not create any new Queue. But Clone() creates a new Queue.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to Copy a Queue using 
// the assignment operator
using System;
using System.Collections;
  
class GFG {
  
    // Main Method
    public static void Main(string[] args)
    {
  
        Queue myQueue = new Queue();
        myQueue.Enqueue("Geeks");
        myQueue.Enqueue("Class");
        myQueue.Enqueue("Noida");
        myQueue.Enqueue("UP");
  
        // Creating a copy using the 
        // assignment operator.
        Queue myQueue2 = myQueue; 
  
        myQueue2.Dequeue();
  
        PrintValues(myQueue);
    }
  
    public static void PrintValues(IEnumerable myCollection)
    {
        // This method prints all the
        // elements in the Stack.
        foreach(Object obj in myCollection)
            Console.WriteLine(obj);
    }
}

chevron_right


Output:

Class
Noida
UP

Example 2: Here myQueue is unchanged.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate the use 
// of Object.Clone() Method 
using System;
using System.Collections;
  
class GFG {
  
    // Main Method
    public static void Main(string[] args)
    {
  
        Queue myQueue = new Queue();
        myQueue.Enqueue("Geeks");
        myQueue.Enqueue("Class");
        myQueue.Enqueue("Noida");
        myQueue.Enqueue("UP");
  
        // Creating copy using Clone() method.
        Queue myQueue2 = (Queue)myQueue.Clone(); 
        myQueue2.Dequeue();
  
        PrintValues(myQueue);
    }
  
    public static void PrintValues(IEnumerable myCollection)
    {
        // This method prints all the
        // elements in the Stack.
        foreach(Object obj in myCollection)
            Console.WriteLine(obj);
        Console.WriteLine();
    }
}

chevron_right


Output:

Geeks
Class
Noida
UP

Reference:



My Personal Notes arrow_drop_up


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.