Cloning queue in c#

12,333

Solution 1

Queue is a reference type, so newQueue and oldQueue holds a pointer to the same object. They are the same ;-)

See this answer about how to do a "deep cloning" using reflection:

Deep Copy using Reflection in an Extension Method for Silverlight?

Solution 2

You have to make a deeper copy:

   //Queue newQueue = oldQueue;
   Queue<string> newQueue = new Queue<string>(oldQueue);
Share:
12,333
Idanis
Author by

Idanis

Updated on June 06, 2022

Comments

  • Idanis
    Idanis almost 2 years

    I have the following code:

    Queue<string> oldQueue = new Queue<string>();
    
    oldQueue.Enqueue("One");
    oldQueue.Enqueue("Two");
    oldQueue.Enqueue("Three");
    
    Queue newQueue = oldQueue;
    string newString = newQueue.Dequeue();
    

    The problem is that once I Dequeue the item from newQueue, the item is also Dequeued from oldQueue. Is there a way to "clone" a queue in a way that removing an item from one queue will keep it's clone queue unchanged?

  • rollsch
    rollsch over 6 years
    It will still hold a pointer to the same object in most cases so its not really a clone. You need to clone the objects it points to as well.
  • Henk Holterman
    Henk Holterman over 6 years
    @rolls - for (immutable and internable) strings that would make no sense at all. For other data it would very much depend.
  • rollsch
    rollsch over 6 years
    Sorry I didn't realise the question was specifically about strings and thought it was asking generally .