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);
Author by
Idanis
Updated on June 06, 2022Comments
-
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 fromoldQueue
. 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 over 6 yearsIt 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 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 over 6 yearsSorry I didn't realise the question was specifically about strings and thought it was asking generally .