In C#, Stack.ToArray() creates a new array and copies every item of a Stack<T> into it. The order is top to bottom: element 0 is the item that Pop() would return first, which is the item pushed last.
That means the array is the reverse of the push order. If you push 1, 2, 3, the array is { 3, 2, 1 }. Think of taking a photo of the pile from above: you see the top plate first. The photo is a snapshot; the plates stay on the stack, and later changes do not alter it. It is handy when you need an index (array[2]), want to sort or print the items, or want to loop and change the stack at the same time.
This is an instance member of Stack<T> (System.Collections.Generic). Call it on a stack variable, such as history.ToArray(...). 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
Call ToArray with no arguments. It returns an array of the same item type.
C#
Stack<string> plates = new Stack<string>();
plates.Push("white");
plates.Push("blue");
plates.Push("red");
string[] snapshot = plates.ToArray(); // { "red", "blue", "white" }
int n = snapshot.Length; // 3
Call
What it does
plates.ToArray()
New array with the items from top to bottom. The stack keeps all its items.
plates.ToArray() (empty stack)
Returns an empty array (length 0), not null.
new List<string>(plates)
The same idea for a List<T>, also top to bottom. See List.
plates.CopyTo(array, 0)
Copy into an array you already have. See CopyTo().
ToArray is O(n) in time and memory, because it allocates a new array and copies every item. For reference types, the array holds the same object references as the stack (a shallow copy). The returned array is yours: sorting it or changing an element does not touch the stack. Because ToArray reads the stack only once, it is also a safe way to loop over the items while you push or pop.
Library declarations
C#
public T[] ToArray();
Parameters
Parameter
Description
None
ToArray() takes no parameters.
Return Value
Return Value
Description
T[]
A new array that holds a copy of the stack's items, top first. If the stack is empty, the array has length 0.
C# Examples
Example 1 — Copy a Stack Into an Array
Convert a stack of names to an array and print it. Then push one more name and see that the array did not change.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Stack<string> names = new Stack<string>();
names.Push("Asha");
names.Push("Ben");
names.Push("Chitra");
string[] snapshot = names.ToArray();
Console.WriteLine(snapshot.Length);
Console.WriteLine(string.Join(", ", snapshot));
Console.WriteLine(snapshot[0]);
names.Push("Dev");
Console.WriteLine(snapshot.Length);
Console.WriteLine(names.Count);
}
}
Output
3
Chitra, Ben, Asha
Chitra
3
4
How It Works
Same length. The stack has three items, so the new array has Length 3.
Top is index 0. The array starts with Chitra, who was pushed last and would be popped first, and ends with Asha, the oldest.
Indexing works now. A stack has no [ ] access, but snapshot[0] reads the top item from the array copy.
A frozen copy. After Push("Dev") the stack has 4 items, but the array still has 3. Arrays have a fixed length and the copy was taken earlier.
Example 2 — Reverse the Order of Words
Push each word of a sentence, then use ToArray to get the words back, newest first. The sentence comes out reversed.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
string sentence = "one two three";
Stack<string> words = new Stack<string>();
foreach (string word in sentence.Split(' ')) {
words.Push(word);
}
string[] reversed = words.ToArray();
Console.WriteLine(string.Join(" ", reversed));
Console.WriteLine(reversed[reversed.Length - 1]);
}
}
Output
three two one
one
How It Works
Split, then push.Split(' ') gives three words, and each one is pushed in turn. three, the last, ends up on top.
ToArray already reverses. Since the array goes top to bottom, it holds three, two, one. No extra sorting step is needed.
Join with spaces.string.Join(" ", reversed) rebuilds a sentence from the array, so the first line prints three two one.
The last cell is the bottom.reversed[reversed.Length - 1] is one, the first word pushed, which sat at the bottom of the stack.
Example 3 — Read the Bottom Item and Handle an Empty Stack
A stack shows only its top, so use ToArray to get at the bottom. Also see what an empty stack gives.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Stack<string> pages = new Stack<string>();
pages.Push("intro");
pages.Push("body");
pages.Push("summary");
string[] items = pages.ToArray();
Console.WriteLine(items[items.Length - 1]);
Stack<string> none = new Stack<string>();
string[] empty = none.ToArray();
Console.WriteLine(empty.Length);
Console.WriteLine(empty == null);
}
}
Output
intro
0
False
How It Works
No bottom access. A stack offers Peek() for the top only. To see the oldest item you need an index.
Last element is the bottom.items[items.Length - 1] reads the final array cell, which is intro, the item pushed first.
An empty stack is fine. Calling ToArray() on an empty stack does not throw. It returns an array with Length 0.
Never null. The array is a real (empty) object, so empty == null is False and a loop over it is safe.
Frequently Asked Questions
It creates a new array and copies every item of the stack into it, from the top to the bottom. The stack is not changed.
Top to bottom. Element 0 is the item that Pop would return first, which is the most recently pushed item. The last element is the oldest item.
No. It only copies them. Count stays the same, and the stack keeps all its items.
An empty array with Length 0. It never returns null.
Call ToArray and then Array.Reverse on the result, or loop over the array from the last index down to 0. The array itself is top first because the stack is last in, first out.