Wednesday, November 18, 2009

Shallow copying a stack

I needed to shallow copy a data structure that contained a few stacks in c#. Without thinking i did the following:

public Foo(Foo p)
Stack = new Stack(p.Stack);

However, this doesn't do what you'd expect. The stack is converted into an enumerable, and then read into the new stack. However, it's backwards. There is no "copy" constructor for stacks.

Here was my easy solution:

public Foo(Foop)
// There is no Stack constructor that take a stack, just the enumerable one
// Since we want a shallow copy, we'll just reverse the list and use that
Stack = new Stack(p.Stack.Reverse());

Since LINQ has a reverse method, we just get the enumerable and reverse it. Then the stack will be created with the same ordering.

No comments: