VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/stack-copyto-method-in-c-sharp/

⇱ Stack.CopyTo() Method in C# - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Stack.CopyTo() Method in C#

Last Updated : 11 Jul, 2025
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. Syntax:
public void CopyTo (T[] array, int arrayIndex);
Parameters:
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.
Exceptions:
  • 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: Example 1:
Output:
GeeksforGeeks
Data Structures
Noida
Geeks Classes
Geeks
Example 2:
Comment

Explore