Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to copy a stack to an existing array in C#

Surabhi Sharma

The Stack<T> generic class in the System.Collections.Generic namespace provides the CopyTo() method, which can be used to copy a stack to an existing one-dimensional array in C#.


public void CopyTo (T[] array, int arrayIndex);


This method takes a one-dimensional array where the elements will be copied from the stack as input.

The CopyTo() method throws an exception if:

  • The input array is null.
  • The number of elements in Stack<T> is greater than the total space available from the input index to the end of the destination array.
  • arrayIndex < 0.

Things to note

  • The CopyTo() method works on one-dimensional arrays.

  • This operation does not change the state of Stack<T>.

  • The elements are copied in the LIFOLast In First Out order to the destination array, similar to the order of items returned the Pop() method.

  • This is an O(n) operation, where nn is the count of the elements in Stack<T>.

Copying a stack to an existing array using CopyTo() method


In the following code, we create a stack of strings.

First, we call the Push() method with the strings Lion, Tiger, and Panther. This inserts all three strings onto the stack, with Panther at the top of the stack.

We then display all the elements of the stack, and we can see that it has Panther at the top, followed by Tiger and Lion.

After this, we create a new array, destinationArray, of strings with a size of five elements. We copy all of the stack elements to this array with the CopyTo() method, starting at index 2.


We then print the elements of the array. We can observe that the array contains all the stack elements in the same LIFO order as the elements returned by the stack’s Pop() method.

We can also observe the two empty spots in the destination array, as we copied the stack starting from array index 2.

using System;
using System.Collections.Generic;

class StackCopyTo
    static void Main()
        Stack<string> stack = new Stack<string>();
        Console.WriteLine("Current Stack Items: \n{0}\n", string.Join(",", stack.ToArray()));
        string[] destinationArray = new string[stack.Count+2];
        Console.WriteLine("Array Items After CopyTo() :\n{0}", string.Join(" , ", destinationArray));




View all Courses

Keep Exploring