Copying from a Collection Type to an Array

The ArrayList, Queue, and Stack types contain overloaded CopyTo() and ToArray() methods for copying their elements to an array. The CopyTo() method copies its elements to an existing one-dimensional array, overwriting the contents of the array beginning at the index you specify. The ToArray() method returns a new array with the contents of the type’s elements.

For example, in the case of a stack, ToArray() returns a new array containing the elements in the stack, and CopyTo() copies the stack over a pre-existing array. Example 16-5 modifies Example 16-4 to demonstrate both methods. The listing is followed by a complete analysis.

Example 16-5. Copying from a Stack type to an array

using System; using System.Collections; namespace StackDemo { class Tester { public void Run() { Stack intStack = new Stack(); // populate the array for (int i = 1;i<5;i++) { intStack.Push(i*5); } // Display the Stack. Console.WriteLine( "intStack values:" ); DisplayValues( intStack ); const int arraySize = 10; int[] testArray = new int[arraySize]; // populate the array for (int i = 1; i < arraySize; i++) { testArray[i] = i * 100; } Console.WriteLine("\nContents of the test array"); DisplayValues( testArray ); // Copy the intStack into the new array, start offset 3 intStack.CopyTo( testArray, 3 ); Console.WriteLine( "\nTestArray after copy: "); DisplayValues( testArray ); // Copy the entire source Stack // to a new standard array. Object[] myArray = intStack.ToArray(); ...

Get Learning C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.