In C#, Stack.CopyTo(array, arrayIndex) copies all items of a Stack<T> into an array that already exists. The top item goes to array[arrayIndex], and the rest follow in order down the stack. The stack itself is not changed.
If ToArray() hands you a new box, CopyTo lets you choose the box and where to start packing. The order is the same as repeated Pop() calls would give: newest first. This is handy when you reuse a big buffer or want the stack items in the middle of a longer array.
This is an instance member of Stack<T> (System.Collections.Generic). Call it on a stack variable, such as history.CopyTo(...). A Stack<T> is a class, so two variables can share one stack. It is last in, first out (LIFO): the newest item sits on top and leaves first. It is not thread-safe; for several threads use ConcurrentStack<T>.
Syntax
Pass the destination array and the position where the top item should go.
Copy from the start of the array. The array must have room for stack.Count items.
stack.CopyTo(buffer, 2)
Copy starting at index 2. Cells before index 2 and after the copied items keep their old values.
stack.CopyTo(small, 0)
If the array has too little room, an ArgumentException is thrown and nothing is copied.
stack.ToArray()
When you do not already have an array. See ToArray().
The room needed is arrayIndex + Count cells. A null array throws ArgumentNullException. A negative arrayIndex, or one past the end of the array, throws ArgumentOutOfRangeException. If the index is valid but there is not enough space after it, you get ArgumentException. The method copies references for reference types (a shallow copy) and is O(n).
Library declarations
C#
public void CopyTo(T[] array, int arrayIndex);
Parameters
Parameter
Description
array
The one-dimensional destination array. It must not be null and must be large enough.
arrayIndex
The zero-based index in array where the top item is copied. It must be 0 or more and not past the end of the array.
Return Value
Return Value
Description
void
Nothing is returned. On success the items are written into array and the stack is unchanged.
C# Examples
Example 1 — Copy a Stack Into a Same-Size Array
Make an array as big as the stack and copy from index 0. The array shows the stack from top to bottom.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Stack<string> letters = new Stack<string>();
letters.Push("A");
letters.Push("B");
letters.Push("C");
string[] copy = new string[letters.Count];
letters.CopyTo(copy, 0);
Console.WriteLine(string.Join(", ", copy));
Console.WriteLine(copy[0]);
Console.WriteLine(letters.Count);
}
}
Output
C, B, A
C
3
How It Works
A right-sized array.new string[letters.Count] gives exactly three empty cells, so there is room for every item.
Start at zero.CopyTo(copy, 0) writes the top item into cell 0 and the lower items into the cells after it.
Reverse of the pushes. The pushes were A, B, C, but the array reads C, B, A, and copy[0] is C.
The stack stays full. Copying does not remove anything, so Count is still 3.
Example 2 — Copy Into the Middle of a Bigger Array
Fill a longer array with -1, then copy the stack starting at index 2. The cells around it keep their values.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
stack.Push(30);
int[] buffer = new int[] { -1, -1, -1, -1, -1, -1 };
stack.CopyTo(buffer, 2);
Console.WriteLine(string.Join(", ", buffer));
}
}
Output
-1, -1, 30, 20, 10, -1
How It Works
A roomy array. It has six cells, each filled with -1 as a marker, so any cell the copy touches stands out.
An offset of 2. The top item 30 lands in buffer[2], then 20 in buffer[3], and 10 in buffer[4].
Outside cells are kept. Indexes 0 and 1 are before the start, and index 5 is after the last copied item. All three still hold -1.
The room check. The copy needs 2 + 3 = 5 cells and the array has 6, so it fits with one cell to spare.
Example 3 — What Goes Wrong With a Small Array
Try to copy three items into an array of two, and then use a negative index. Print the exception type for each.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Stack<int> stack = new Stack<int>(new int[] { 1, 2, 3 });
try {
int[] small = new int[2];
stack.CopyTo(small, 0);
} catch (ArgumentException ex) {
Console.WriteLine(ex.GetType().Name);
}
try {
int[] big = new int[5];
stack.CopyTo(big, -1);
} catch (ArgumentOutOfRangeException ex) {
Console.WriteLine(ex.GetType().Name);
}
int[] fine = new int[3];
stack.CopyTo(fine, 0);
Console.WriteLine(fine[2]);
}
}
Output
ArgumentException
ArgumentOutOfRangeException
1
How It Works
Not enough room. Three items cannot fit in a two-cell array, so the first call throws ArgumentException.
A bad start position. An arrayIndex of -1 is outside the array, so the second call throws the more specific ArgumentOutOfRangeException.
Names only. The code prints the exception type name and not the message, since message wording can vary between .NET versions.
The fixed copy. A three-cell array and index 0 work. The last cell, fine[2], holds the bottom item, 1, because the array starts with the top (3).
Frequently Asked Questions
It copies all items of the stack into an existing array, starting at the arrayIndex you give. The top item goes first. The stack is not changed.
ToArray creates and returns a new array. CopyTo writes into an array you already have, at a position you choose, which can avoid an extra allocation. Both use top-to-bottom order.
An ArgumentException is thrown. The array must have at least arrayIndex + Count cells.
It must be 0 or more and not greater than the array length, and there must be enough cells after it for all the items. A negative value or one past the end throws ArgumentOutOfRangeException.
No. For reference types, it copies the references, so the array and the stack point to the same objects. That is a shallow copy.