In C#, HashSet.CopyTo(array) copies the items of the set into an array you already created. It is how you turn a set into an array when you need positions, an index, or an API that only accepts arrays.
There are three forms. CopyTo(array) starts at position 0. CopyTo(array, arrayIndex) starts at a position you choose. CopyTo(array, arrayIndex, count) copies only the first count items. The method does not promise the order of the copied items, so sort the array before you print it. The set itself is not changed.
This is an instance member of HashSet<T> (System.Collections.Generic). Call it on a set variable, such as numbers.CopyTo(...). A HashSet<T> is a class, so two variables can share one set. It keeps unique items only and does not promise any order.
Syntax
Make an array that is big enough, then pass it to CopyTo. The three overloads add a start position and a count.
C#
HashSet<int> set = new HashSet<int> { 30, 10, 20 };
int[] a = new int[set.Count];
set.CopyTo(a); // fills a from position 0
int[] b = new int[5];
set.CopyTo(b, 1); // fills b from position 1
int[] c = new int[5];
set.CopyTo(c, 0, 2); // copies only 2 items
Call
What it does
set.CopyTo(a)
Copies every item into a, starting at position 0. a must be big enough.
set.CopyTo(a, 2)
Starts writing at position 2. There must be room for all items from there on.
set.CopyTo(a, 0, 2)
Copies only count (here 2) items. Which 2 items is not promised.
If the array is too small, ArgumentException is thrown. A negative arrayIndex or count throws ArgumentOutOfRangeException, and a null array throws ArgumentNullException. For a quick new array, ToArray() from System.Linq is another option.
Library declarations
C#
public void CopyTo(T[] array);
public void CopyTo(T[] array, int arrayIndex);
public void CopyTo(T[] array, int arrayIndex, int count);
Parameters
Parameter
Description
array
Required. The destination one-dimensional array. It must already exist and be long enough. It must not be null.
arrayIndex
Optional. The position in array where the first item is written. It must be 0 or more. Default is 0.
count
Optional. How many items to copy. It must be 0 or more, and must fit in the array from arrayIndex on. Without it, all items are copied.
Return Value
Return Value
Description
void
Nothing is returned. The array is filled in place. The set is unchanged.
C# Examples
Example 1 — Copy a Set to an Array
Create an array of the right size, copy the set into it, and sort the array so the printed result is stable.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
HashSet<int> set = new HashSet<int> { 30, 10, 20 };
int[] arr = new int[set.Count];
set.CopyTo(arr);
Array.Sort(arr);
Console.WriteLine(string.Join(", ", arr));
Console.WriteLine(arr.Length);
}
}
Output
10, 20, 30
3
How It Works
Right-sized array.new int[set.Count] makes an array with exactly one slot for each item.
Copy fills it.set.CopyTo(arr) writes the three numbers into the array. The order they land in is up to the set.
Sort for a stable print.Array.Sort(arr) puts the numbers in ascending order, so the output is always 10, 20, 30.
Array length. The array has 3 slots, because it was sized from Count.
Example 2 — Copy Into the Middle of a Bigger Array
Fill a five-slot array with -1, copy three items starting at position 1, then sort only the copied part.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
HashSet<int> set = new HashSet<int> { 30, 10, 20 };
int[] arr = { -1, -1, -1, -1, -1 };
set.CopyTo(arr, 1);
Array.Sort(arr, 1, 3);
Console.WriteLine(string.Join(", ", arr));
Console.WriteLine(arr.Length);
}
}
Output
-1, 10, 20, 30, -1
5
How It Works
Padding on both sides. The array starts as five copies of -1, so you can see exactly which slots CopyTo overwrites.
Start at position 1.CopyTo(arr, 1) writes the three items into slots 1, 2, and 3. Slots 0 and 4 are not touched.
Sort only the middle.Array.Sort(arr, 1, 3) sorts three slots starting at position 1, so the two -1 values stay at the edges.
Length unchanged. The array is still 5 long. CopyTo never resizes an array.
Example 3 — Copy Only Some Items and Handle a Small Array
Use the count overload to copy two items, then see what happens when the array is too small.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
HashSet<int> set = new HashSet<int> { 1, 2, 3, 4, 5 };
int[] arr = new int[4];
set.CopyTo(arr, 0, 2);
Console.WriteLine(set.Contains(arr[0]));
Console.WriteLine(set.Contains(arr[1]));
Console.WriteLine(arr[2]);
HashSet<int> three = new HashSet<int> { 1, 2, 3 };
try {
three.CopyTo(new int[2]);
} catch (ArgumentException) {
Console.WriteLine("array too small");
}
}
}
Output
True
True
0
array too small
How It Works
Copy two only.CopyTo(arr, 0, 2) copies two items starting at position 0. Which two items is not promised, so the program does not print them.
Check by lookup. The first two slots hold real items from the set, so Contains prints True for both. This works whatever order was used.
The rest stays default.arr[2] was never written, so it is still 0, the default of an int.
Too small. Three items cannot fit in a two-slot array, so CopyTo throws ArgumentException and the catch block prints a message.
Frequently Asked Questions
It copies the items of the set into an array that you provide. The set is not changed.
The order is not promised. Sort the array with Array.Sort before you print or compare it.
CopyTo throws ArgumentException. Create the array with set.Count slots, or more, before you copy.
Use CopyTo(array, arrayIndex, count). It copies count items, but you cannot choose which items they are.
Yes. With using System.Linq you can write set.ToArray(), which creates the array for you. You can also pass the set to the List constructor and sort that list.