
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Replacing the Stack and Queue with Their Generic Counterparts
|
235
The output for this method is shown here:
foreach: 1
foreach: 2
foreach: 3
1
2
3
For the Stack object, the code is as follows.
public static void CloneStack( )
{
// Create a generic Stack object.
Stack<int> numericStack = new Stack<int>( );
// Populate Stack.
numericStack.Push(1);
numericStack.Push(2);
numericStack.Push(3);
// Clone the numericStack object.
Stack<int> clonedNumericStack = new Stack<int>(numericStack);
// This does a simple peek at the values not a pop.
foreach (int i in clonedNumericStack)
{
Console.WriteLine("foreach: " + i.ToString( ));
}
// De-populate Stack and display items.
Console.WriteLine(clonedNumericStack.Pop( ).ToString( ));
Console.WriteLine(clonedNumericStack.Pop( ).ToString( ));
Console.WriteLine(clonedNumericStack.Pop( ).ToString( ));
}
The output for this method is shown here:
foreach: 1
foreach: 2
foreach: 3
1
2
3
This constructor creates a new instance of the Queue or Stack class containing the ele-
ments copied from the
IEnumerable<T> type.
See Also
See the “System.Collections.Stack Class,” “System.Collections.Generic.Stack Class,”
“System.Collections.Queue Class,” and “System.Collections.Generic.Queue Class”
topics in the MSDN documentation.