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:
CSHARP
CSHARP
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.
// C# code to illustrate the
// Stack.CopyTo() Method
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Stack
Stack myStack = new Stack();
// Inserting the elements into the Stack
myStack.Push("Geeks");
myStack.Push("Geeks Classes");
myStack.Push("Noida");
myStack.Push("Data Structures");
myStack.Push("GeeksforGeeks");
// Creating a string array arr
string[] arr = new string[myStack.Count];
// Copying the elements of
// stack into array arr
myStack.CopyTo(arr, 0);
// Displaying the elements
// in array arr
foreach(string str in arr)
{
Console.WriteLine(str);
}
}
}
Output:
Example 2:
GeeksforGeeks Data Structures Noida Geeks Classes Geeks
// C# code to illustrate the
// Stack.CopyTo() Method
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Stack
Stack myStack = new Stack();
// Inserting the elements
// into the Stack
myStack.Push(2);
myStack.Push(3);
myStack.Push(4);
myStack.Push(5);
myStack.Push(6);
// Creating an Integer array arr
int[] arr = new int[myStack.Count];
// Copying the elements of
// stack into array arr
myStack.CopyTo(arr, 0);
// Displaying the elements
// in array arr
foreach(int i in arr)
{
Console.WriteLine(i);
}
}
}