This method(comes under System.Collections namespace) is used to copy the Stack to an existing 1-D Array which starts from the specified array index. The elements are copied onto the array in last-in-first-out (LIFO) order, similar to the order of the elements returned by a succession of calls to Pop. This method is an O(n) operation, where n is Count.
public void CopyTo (T array, int arrayIndex);
array: It is the one-dimensional Array that is the destination of the elements copied from Stack. The Array must have zero-based indexing.
arrayIndex: It is the zero-based index in array at which copying begins.
- ArgumentNullException : If an array is null.
- ArgumentOutOfRangeException : If the index is less than zero.
- ArgumentException : If the array is multidimensional or the number of elements in the source Stack is greater than the available space from index to the end of the destination array.
- InvalidCastException : If the type of the source Stack cannot be cast automatically to the type of the destination array.
Below given are some examples to understand the implementation in a better way:
GeeksforGeeks Data Structures Noida Geeks Classes Geeks
6 5 4 3 2