First example. Here we use the Array.Copy method overload that copies one source array to a destination array. Both arrays must have at least the length specified in the third parameter.
Step 1 We create a new int array with 5 elements. We assign some integers to the elements.
Step 2 Next we allocate an empty array of 5 ints. These are all 0 when the array is created.
Step 3 We invoke Copy, with 3 arguments—the source array, the destination array, and the length we want to copy.
Step 4 The target array is written to the Console. It has the same contents as the source array.
using System;
// Step 1: instantiate the source array.
int[] source = new int[5];
source[0] = 1;
source[1] = 2;
source[2] = 3;
source[3] = 4;
source[4] = 5;
// Step 2: instantiate and allocate the target array.
int[] target = new int[5];
// Step 3: copy the source to the target.
Array.Copy(source, target, 5);
// Step 4: display the target array.
foreach (int value in target)
{
Console.WriteLine(value);
}1
2
3
4
5
Range example. Here we copy one range in an array to another range in the second array. This style of code can cause exceptions. We have to be careful with checking the array bounds.
Next The example copies the first 3 elements from the source array to a smaller target array.
using System;
// Source array.
int[] source = new int[5];
source[0] = 5;
source[1] = 4;
source[2] = 3;
source[3] = 2;
source[4] = 1;
// Instantiate the target.
int[] target = new int[3];
// Copy first 3 elements in source to target.
Array.Copy(source, 0, target, 0, 3);
// Display the result.
foreach (int value in target)
{
Console.WriteLine(value);
}5
4
3
Array.ConstrainedCopy. This method validates arrays before it copies them. The regular Array.Copy method will silently copy a byte array to an int array.
Info The Array.ConstrainedCopy method instead throws an exception. This can improve reliability.
Important ConstrainedCopy throws an exception. It allows no conversions of elements to take place.
using System;
byte[] original = new byte[10];
original[0] = 1;
int[] destination = new int[10];
// This will work if you call Array.Copy instead.
Array.ConstrainedCopy(original, 0, destination, 0, original.Length);Unhandled Exception:
System.ArrayTypeMismatchException: Array.ConstrainedCopy will only work
on array types that are provably compatible, without any form of boxing,
unboxing, widening,or casting of each array element.
Change the array types....
Performance. The Array.Copy method is fast for most uses. It is simpler than manually copying all the elements. Array.Copy can be optimized in .NET.
Version 1 This version of the code copies 25 array elements with Array.Copy. The elements are single bytes.
Version 2 This code uses a for-loop to copy each of the 25 elements—it uses array element assignment.
Result In .NET 5 for Linux in 2021, using Array.Copy is faster. In my testing, after around 15 elements, using Array.Copy is faster.
Further A speedup from Array.Copy can be attained with string arrays, or other kinds of arrays.
Also The Buffer class improves performance—with it, we must specify byte sizes.
using System;
using System.Diagnostics;
const int _max = 10000000;
// Set up benchmark.
var data = new byte[200];
for (int i = 50; i < 75; i++)
{
data[i] = (byte)i;
}
var buffer = new byte[100];
var s1 = Stopwatch.StartNew();
// Version 1: use Array.Copy.
for (int i = 0; i < _max; i++)
{
Array.Copy(data, 50, buffer, 0, 25);
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use for-loop to copy.
for (int i = 0; i < _max; i++)
{
for (int z = 0; z < 25; z++)
{
buffer[z] = data[z + 50];
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); 7.17 ns Array.Copy
13.86 ns for
Copy, exceptions. Here we look at Array.Copy exceptions. First, you cannot copy from or to a null reference array. This raises the ArgumentNullException.
List. You can use the List generic class instead of Array to copy collections of elements. With the List class, you can copy into a new List simply by using the constructor.
A summary. Array.Copy can copy entire arrays or just sections of arrays. You must remember to allocate your arrays with adequate Length before calling Array.Copy.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.