Array.Copy
Learn to copy part of an array with Array.Copy.
Array.Copy
Array.Copy copies elements from one array to another. The most common form takes three parameters: Array.Copy(source, destination, length). It takes that many elements from the source and writes them at the start of the destination.
For example, after int[] src = { 1, 2, 3 }; int[] dst = new int[3]; Array.Copy(src, dst, 3);, the dst array becomes { 1, 2, 3 }. The destination must be allocated beforehand.
Five-parameter Array.Copy
For finer control, use the five-parameter form: Array.Copy(source, sourceIndex, destination, destinationIndex, length). This form copies a slice of the given length starting at a source index into a destination index.
For example, Array.Copy(src, 1, dst, 0, 2) takes two elements starting at index 1 of src and writes them at index 0 of dst. This way you copy only a slice of the array.
Exercise Copy a specific range
From the given int[] src = { 5, 10, 15, 20, 25 }; array, copy with Array.Copy(src, 1, dst, 0, 3) starting at source index 1 with length 3 into int[] dst = new int[3];. Then print dst[0] with Console.WriteLine.
Show example solution
Copy with Array.Copy(src, 1, dst, 0, 3);, then print with Console.WriteLine(dst[0]);.
Example solution:
using System;
class Program
{
static void Main()
{
int[] src = { 5, 10, 15, 20, 25 };
int[] dst = new int[3];
// Copy 3 elements from src index 1 into dst and print dst[0]
Array.Copy(src, 1, dst, 0, 3);
Console.WriteLine(dst[0]);
}
}
Test yourself
-
What does dst[0] print after Array.Copy?
int[] src = { 10, 20, 30, 40 }; int[] dst = new int[4]; Array.Copy(src, dst, 4); Console.WriteLine(dst[0]);- 20
- 30
- 40
- 10
Show answer
10 — Correct. All elements are copied; dst[0] is 10.
-
Array.Copy short call
int[] src = { 1, 2, 3 }; int[] dst = new int[3]; ____ Console.WriteLine(dst[0]);Show answer
int[] src = { 1, 2, 3 }; int[] dst = new int[3]; Array.Copy(src, dst, 3); Console.WriteLine(dst[0]); -
Match each expression to its meaning
- Array.Copy(src, dst, 3)
- Copies all
- Array.Copy(src, 0, dst, 0, 2)
- Copies first 2
- new int[3]
- 3-cell array
- dst[0]
- First element