Stack<T>::CopyTo Method (array<T>^, Int32)
Assembly: System (in System.dll)
Parameters
- array
-
Type:
array<T>^
The one-dimensional Array that is the destination of the elements copied from Stack<T>. The Array must have zero-based indexing.
- arrayIndex
-
Type:
System::Int32
The zero-based index in array at which copying begins.
| Exception | Condition |
|---|---|
| ArgumentNullException | array is null. |
| ArgumentOutOfRangeException | arrayIndex is less than zero. |
| ArgumentException | The number of elements in the source Stack<T> is greater than the available space from arrayIndex to the end of the destination array. |
The following code example demonstrates several methods of the Stack<T> generic class, including the CopyTo method.
The code example creates a stack of strings with default capacity and uses the Push method to push five strings onto the stack. The elements of the stack are enumerated, which does not change the state of the stack. The Pop method is used to pop the first string off the stack. The Peek method is used to look at the next item on the stack, and then the Pop method is used to pop it off.
The ToArray method is used to create an array and copy the stack elements to it, then the array is passed to the Stack<T> constructor that takes IEnumerable<T>, creating a copy of the stack with the order of the elements reversed. The elements of the copy are displayed.
An array twice the size of the stack is created, and the CopyTo method is used to copy the array elements beginning at the middle of the array. The Stack<T> constructor is used again to create a copy of the stack with the order of elements reversed; thus, the three null elements are at the end.
The Contains method is used to show that the string "four" is in the first copy of the stack, after which the Clear method clears the copy and the Count property shows that the stack is empty.
Available since 8
.NET Framework
Available since 2.0
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1