OneBite.Dev - Coding blog in a bite size

Copy An Array In C#

Code snippet for how to Copy An Array In C# with sample and detail explanation

Copying an array might seem like a simple task but it’s not always straightforward, particularly in programming languages like C#. This article takes a detailed look at how to properly copy an array in C# with a code snippet and a step-by-step explanation.

Code snippet for Copying an Array in C#

Consider the following C# code snippet:

int[] sourceArray = {1, 2, 3, 4, 5};
int[] destinationArray = new int[5];
sourceArray.CopyTo(destinationArray, 0);

Code Explanation for Copying an Array in C#

Let’s understand this code snippet step by step.

Initially, we define a source array named sourceArray, and this array contains five integers:

int[] sourceArray = {1, 2, 3, 4, 5};

The next step is to create a destination array, which we’ll call destinationArray. This is the array to which you want to copy the elements of the source array. It’s necessary to specify the size of this array, which in this case is 5:

int[] destinationArray = new int[5];

Now, to actually copy the elements of sourceArray into destinationArray, we’re making use of the CopyTo method, which is a built-in array method in C#.

sourceArray.CopyTo(destinationArray, 0);

This CopyTo method has two parameters:

  • The first parameter is the array you want to copy to. In this case, destinationArray.

  • The second parameter is the index in the destination array at which storing of elements will begin. Here, it’s 0, indicating that the copying operation will start from the very first index of destinationArray.

Would you want to print the elements of the destinationArray after the copying operation, you can do this:

foreach(int i in destinationArray) {
    Console.WriteLine(i);
}

This will output:

1
2
3
4
5

So, as seen above, all elements of sourceArray have been successfully copied into destinationArray.

c-sharp