C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Step 1: We create a new int array with 5 elements. We assign some integers to the elements.
Int ArrayStep 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.
C# program that uses Array.Copy method
using System;
class Program
{
static void Main()
{
// 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.
Console.WriteLine("--- Target array ---");
foreach (int value in target)
{
Console.WriteLine(value);
}
}
}
Output
--- Target array ---
1
2
3
4
5
Next: The example copies the first 3 elements from the source array to a smaller target array.
C# program that copies array section
using System;
class Program
{
static void Main()
{
// 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.
Console.WriteLine("--- Destination array ---");
foreach (int value in target)
{
Console.WriteLine(value);
}
}
}
Output
--- Destination array ---
5
4
3
Info: The Array.ConstrainedCopy method instead throws an exception. This can improve reliability.
ArrayTypeMismatch ExceptionProgram: An array of bytes is created and a destination array of ints is also allocated. The Array.ConstrainedCopy method is then called.
Byte ArrayImportant: ConstrainedCopy throws an exception. It allows no conversions of elements to take place.
C# program that uses Array.ConstrainedCopy
using System;
class Program
{
static void Main()
{
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);
}
}
Output
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....
Also: Each array must have adequate length for the complete copy operation. Otherwise we get an ArgumentException.
Array Length