Updated on
To copy an array in C#, we fill a new array with its elements using Array.Copy(), CopyTo(), Clone(), a range, a span or a collection expression. Plain assignment copies nothing. It gives us a second variable that points at the same array.
All of these methods make a shallow copy: the new array holds references to the same objects. When we need independent objects, we create them ourselves with LINQ or a loop. At the end, we benchmark every approach except LINQ’s ToArray() on .NET 10.
Let’s start.
Instantiating the Initial Array
First, let’s create a class in its own file that is going to represent the elements of our array:
public class Article
{
public string? Title { get; set; }
public DateTime LastUpdate { get; set; }
public override string ToString()
{
return $" Title: {Title} | Last update: {LastUpdate:yyyy-MM-dd}";
}
}
Next, let’s create some Article objects and then fill our source array:
var article1 = new Article { Title = "C# Intermediate - Delegates", LastUpdate = new DateTime(2022, 11, 07) };
var article2 = new Article { Title = "Events in C#", LastUpdate = new DateTime(2022, 01, 22) };
var article3 = new Article { Title = "Selection Sort in C#", LastUpdate = new DateTime(2022, 01, 13) };
Article[] initialArray = [article1, article2, article3];
Now that we have our initialArray ready, let’s try some approaches. We put each approach in its own public method of a public ElementCopier class. Each method takes the source array as an Article[] initialArray parameter and returns the result.
Copying Elements by Assignment
The first and easiest way to copy values from one array to another is by copying the entire array by assignment (using = operator):
var destination = initialArray;
However, this is not always a good solution. Since arrays work as a reference type, when we change a value inside the initialArray (or vice-versa), both arrays will change. In other words, we are not creating a new array, we are just using two variables pointing to the same memory address.
That said, let’s solve this problem with our next approach.
Copying Elements Using Array.Copy
This approach uses a static method from the Array class that lives under the System namespace.
So, let’s create our destinationArray and use the Copy method:
Article[] destinationArray = new Article[initialArray.Length]; Array.Copy(initialArray, destinationArray, initialArray.Length);
This method copies a range of elements depending on the parameters we pass. The first and the second parameters represent our source and destination array. The third parameter, specified as int or long, is the number of elements we are going to copy. In this case, we are copying all the elements from the source array.
If we don’t need to copy an entire array, the Array class provides an overload to this method:
Array.Copy(initialArray, 1, destinationArray, 0, initialArray.Length - 1);
Both first and second parameters are about the source array, representing the source array and the index that the copy will begin. The third and the fourth parameter represents, respectively, the destination array and the index at which storing begins. The last parameter is the number of elements to copy.
In this scenario, if our destinationArray starts empty, it will consist of the second and third elements from the initialArray and its third slot will be empty:
- Title: Events in C# | Last update: 2022-01-22 - Title: Selection Sort in C# | Last update: 2022-01-13 - (empty slot)
Copying Elements Using Clone
When we use the Clone method, it will return a shallow copy of the System.Array. In other words, our destination array will have references to the elements of our source array.
The Microsoft Learn page for Array.Clone() says a shallow copy “does not copy the objects that the references refer to.”
Let’s implement our clone:
var destinationArray = (Article[])initialArray.Clone();
Clone() is declared to return object, even though the object it returns is an Article[]. Hence, we can’t iterate over the result until we cast it back to the array type, which is what (Article[]) does.
This method doesn’t allow us to make a partial copy from the source array.
Copying Elements Using CopyTo
This approach is very similar to the method above. However, different from the Clone, we will need to provide some input parameters and we are not going to receive any return type.
Let’s instantiate our destination array of articles and set its size:
var destinationArray = new Article[initialArray.Length];
Then, let’s copy the elements from the source array:
initialArray.CopyTo(destinationArray, 0);
The first parameter represents the array that will receive the elements. The second represents the index in the destinationArray that will start receiving elements.
The destination has to be big enough for the whole source array from that index on. If it is too short, CopyTo() throws an ArgumentException.
Using Range to Copy Array Elements
Microsoft introduced the range concepts since C# 8.0, and this is another way we can use to copy elements from one array to another.
With this technique, we can specify the initial and the final index we want to copy within the brackets:
var destinationArray = initialArray[1..3];
In this example, our destinationArray will receive the elements starting from index 1 up to index 3 (index 3 not inclusive).
On the other hand, if we want to copy the array by complete, we don’t need to specify the range between brackets[..]:
var destinationArray = initialArray[..];
On an array, a range creates a new array, [..] included, so both forms give us a real copy of the elements. Ranges can do a lot more than copy, and we cover them in our article on array slicing.
Copying Elements With Spans and Collection Expressions
C# also has two newer ways to copy an array.
The first one goes through Span<T>. AsSpan() gives us a span over the source array without copying anything, and its CopyTo() method writes the elements into the destination:
var destinationArray = new Article[initialArray.Length]; initialArray.AsSpan().CopyTo(destinationArray);
Like Array.CopyTo(), it throws an ArgumentException when the destination is too short. If we would rather check than catch, TryCopyTo() returns false and copies nothing.
The second one is a collection expression, available since C# 12. The spread operator .. copies every element of the source into a new array:
Article[] destinationArray = [.. initialArray];
This is one of the shortest ways to copy a whole array, and the target type decides what we get back. Here it is Article[], so we get a new array of the same length.
Both of them make a shallow copy, the same as Array.Copy().
Copying Array Elements Using Linq
We can use Linq to achieve this result:
var destinationArray = initialArray.ToArray();
ToArray() reads the source and returns a new array with the same references, so this is a shallow copy too.
If we want a deep copy of our elements, we can use Select() with a lambda expression that creates a new instance of Article:
var destinationArray = initialArray
.Select(x => new Article { Title = x.Title, LastUpdate = x.LastUpdate })
.ToArray();
Copying Elements Manually
Finally, we are going to copy elements using iteration statements. In this case, we are going to use the for loop.
Let’s define our destination array:
var destinationArray = new Article[initialArray.Length];
And now, let’s implement our for statement:
for (int index = 0; index < initialArray.Length; index++)
destinationArray[index] = new Article
{
Title = initialArray[index].Title,
LastUpdate = initialArray[index].LastUpdate
};
return destinationArray;
As in the Linq approach, in this implementation, we are instantiating a new Article on each iteration to create a deep copy of elements.Â
How Do We Deep Copy an Array in C#?
An array copy in C# is shallow by default. Array.Copy(), CopyTo(), Clone(), a range, a span copy and a collection expression all build a new array, but they fill it with the same references the source array holds.
For an array of int, double or another simple value type, that is already a full copy. For an array of objects, both arrays point at the same Article instances.
The sample shows it. After an Array.Copy(), changing the title through destinationArray[0] also changes initialArray[0], because there is only one object behind both slots.
To deep copy an array, we create a new object for every element. A LINQ Select() that calls new Article { ... } does that, and so does the for loop from the previous section.
If our class holds other objects, we have to copy those as well, level by level, or the copy is only one level deep.
Here is that check in the sample’s Program.cs, where InstantiateInitialArray() returns a new array of our three articles and elementCopier is an ElementCopier instance. We copy with Array.Copy() in CopyUsingArrayClass() and then change the first title through the copy:
var source = InstantiateInitialArray();
var copy = elementCopier.CopyUsingArrayClass(source);
copy[0].Title = "Changed through the copy";
Console.WriteLine($" -{source[0]}");
The source array prints the new title:
- Title: Changed through the copy | Last update: 2022-11-07
Copying the objects themselves is a topic of its own. Our article on deep copying an object covers MemberwiseClone(), copy constructors and the other options.
Before we measure anything, here is every approach from this article side by side:
| Way | Code | New array | Partial copy | Elements in the copy |
|---|---|---|---|---|
| Assignment | var copy = source; | No, same array | No | Same array |
Array.Copy() | Array.Copy(source, copy, source.Length); | We create it first | Yes, start index and length | Same references (shallow) |
CopyTo() | source.CopyTo(copy, 0); | We create it first | No, whole source at a destination index | Same references (shallow) |
Clone() | (Article[])source.Clone(); | Yes | No | Same references (shallow) |
| Range | source[..] or source[1..3] | Yes | Yes | Same references (shallow) |
| Span | source.AsSpan().CopyTo(copy); | We create it first | Yes, slice the span first | Same references (shallow) |
| Collection expression | Article[] copy = [.. source]; | Yes | No | Same references (shallow) |
LINQ ToArray() | source.ToArray(); | Yes | No | Same references (shallow) |
LINQ Select() | source.Select(x => new Article { ... }).ToArray(); | Yes | No | New objects (deep) |
for loop | copy[i] = new Article { ... }; | We create it first | Yes | New objects (deep) |
Only the last two rows give us independent objects, and only the first row skips creating a new array. Everything in between makes a shallow copy.
Which Way of Copying an Array Is Fastest?
Plain assignment wins every run, because it copies nothing. It returns the same array, so it takes about a nanosecond and allocates zero bytes.
Among the real copies, Array.Copy(), CopyTo(), Clone(), a range, AsSpan().CopyTo() and a collection expression finish close together. In our benchmark on .NET 10, all six copied 1,000 references in roughly 0.38 to 0.40 microseconds and allocated the same 8,024 bytes. Under the hood they all end in the same bulk memory copy, so the choice between them comes down to which one reads best in our code.
The deep copies do a different job, and they cost much more. LINQ with Select() and the manual for loop took about 13 to 28 times longer, because they create a new Article for every element and allocate five times the memory. A deep copy is worth that price only when the elements must be independent.
To find out which way is fastest, we’ve prepared a benchmark that compares all of the above methods except ToArray() on an array of 1,000 elements and an array of 10,000 elements:
[MemoryDiagnoser]
public class ElementCopierBenchmark
{
private static readonly ElementCopier elementCopier = new();
private Article[] benchMarkSourceArray = [];
[Params(1000, 10000)]
public int Size { get; set; }
[GlobalSetup]
public void Setup()
{
benchMarkSourceArray = Enumerable
.Repeat(new Article { Title = "Title", LastUpdate = DateTime.Now }, Size)
.ToArray();
}
[Benchmark]
public Article[] CopyUsingAssignment() => elementCopier.CopyUsingAssignment(benchMarkSourceArray);
[Benchmark]
public Article[] CopyUsingArrayClass() => elementCopier.CopyUsingArrayClass(benchMarkSourceArray);
[Benchmark]
public Article[] CopyUsingClone() => elementCopier.CopyUsingClone(benchMarkSourceArray);
[Benchmark]
public Article[] CopyUsingCopyTo() => elementCopier.CopyUsingCopyTo(benchMarkSourceArray);
[Benchmark]
public Article[] CopyUsingRange() => elementCopier.CopyUsingRange(benchMarkSourceArray);
[Benchmark]
public Article[] CopyUsingSpan() => elementCopier.CopyUsingSpan(benchMarkSourceArray);
[Benchmark]
public Article[] CopyUsingCollectionExpression() => elementCopier.CopyUsingCollectionExpression(benchMarkSourceArray);
[Benchmark]
public Article[] CopyUsingLinq() => elementCopier.CopyUsingLinq(benchMarkSourceArray);
[Benchmark]
public Article[] ManuallyCopy() => elementCopier.ManuallyCopy(benchMarkSourceArray);
}
Every benchmark method returns the copied array, so BenchmarkDotNet consumes the result and the JIT cannot skip the copy. [MemoryDiagnoser] adds the Allocated column, which shows exactly which methods create a new array.
The class goes in its own console project, which references the project that holds our Article and ElementCopier classes, with the ElementCopier methods named as the benchmark calls them. We add the BenchmarkDotNet package to it, start the class file with using BenchmarkDotNet.Attributes;, and call BenchmarkRunner.Run<ElementCopierBenchmark>(); from its Program.cs, after using BenchmarkDotNet.Running;. Let’s run it in Release mode:
| Method | Size | Mean | Error | StdDev | Allocated | |------------------------------ |------ |---------------:|--------------:|--------------:|----------:| | CopyUsingAssignment | 1000 | 0.7317 ns | 0.0077 ns | 0.0072 ns | - | | CopyUsingArrayClass | 1000 | 389.4309 ns | 6.9869 ns | 6.1937 ns | 8024 B | | CopyUsingClone | 1000 | 403.5720 ns | 7.9413 ns | 7.7994 ns | 8024 B | | CopyUsingCopyTo | 1000 | 377.3453 ns | 7.6135 ns | 14.4855 ns | 8024 B | | CopyUsingRange | 1000 | 378.5272 ns | 7.6381 ns | 14.3462 ns | 8024 B | | CopyUsingSpan | 1000 | 384.9582 ns | 5.9215 ns | 4.9447 ns | 8024 B | | CopyUsingCollectionExpression | 1000 | 393.2183 ns | 7.8579 ns | 14.1694 ns | 8024 B | | CopyUsingLinq | 1000 | 7,836.7718 ns | 111.4532 ns | 98.8004 ns | 40072 B | | ManuallyCopy | 1000 | 5,276.1274 ns | 89.0754 ns | 83.3212 ns | 40024 B | | CopyUsingAssignment | 10000 | 0.8077 ns | 0.0450 ns | 0.0421 ns | - | | CopyUsingArrayClass | 10000 | 3,417.6073 ns | 58.8624 ns | 76.5377 ns | 80024 B | | CopyUsingClone | 10000 | 3,346.9609 ns | 63.0485 ns | 118.4204 ns | 80024 B | | CopyUsingCopyTo | 10000 | 3,275.3264 ns | 63.6833 ns | 87.1705 ns | 80024 B | | CopyUsingRange | 10000 | 3,239.5377 ns | 48.6415 ns | 45.4993 ns | 80024 B | | CopyUsingSpan | 10000 | 3,448.7214 ns | 68.3325 ns | 112.2722 ns | 80024 B | | CopyUsingCollectionExpression | 10000 | 3,353.8346 ns | 24.7439 ns | 23.1455 ns | 80024 B | | CopyUsingLinq | 10000 | 91,263.4694 ns | 1,763.2504 ns | 1,810.7284 ns | 400072 B | | ManuallyCopy | 10000 | 63,867.8082 ns | 1,194.6837 ns | 2,467.2292 ns | 400024 B |
CopyUsingAssignment is in a class of its own. It doesn’t copy the array elements at all. It returns a second reference to the source array, and the Allocated column shows zero bytes.
The next six methods all create a new array and copy the references into it, and they allocate exactly the same memory. Their timings are close enough that we are free to choose the one we like more. But we must take into account whether we need a deep copy or not.
CopyUsingLinq and ManuallyCopy are the slow pair because they do more work: they create one new Article per element. That is the cost of a deep copy, and it shows in both the time and the memory columns.
Comparing the two sizes, every real copy takes about 8 to 12 times longer on ten times the elements.
Conclusion
In this article, we have learned many ways to copy elements from one array to another, using deep and shallow copy.Â
We have seen a benchmark comparison between them that leads us to choose the best method when we are writing our code.
If you work with lists rather than arrays, the same shallow and deep copy rules apply, and our article on cloning a list walks through them for List<T>.
Tested with .NET 10.0.10, BenchmarkDotNet 0.15.8 and MSTest 4.5.2.
