This post will discuss how to create a copy of an array in C#.

1. Using Array.CopyTo method

The idea is to create a new array of the same length as the source array, and call the Array.CopyTo() method to copy all elements from the source array to the destination array starting at the specified destination array index.

Download  Run Code

 
The Array.Copy() method can also work here. The following code example shows how it can be used to copy the specified number of elements from the source array to the destination array.

Download  Run Code

 
The Array.Copy() method is overloaded to copy a range of array elements starting at the specified source index to another array starting at the specified destination index.

Download  Run Code

2. Using LINQ

LINQ’s Take() method is often used to get the first few elements from a sequence. To create a copy of an array, you can pass the number of elements in the source array to the Take() method and get the array representation of the returned sequence using ToArray() method.

Download  Run Code

3. Using Array.Clone method

Another plausible option is to use the Array.Clone method to create a shallow copy of the array. The following code example demonstrates its usage. Note that the Array.Clone method returns an Object and a cast is needed to convert it to an array.

Download  Run Code

4. Using Buffer.BlockCopy method

The Buffer.BlockCopy method copies the specified number of bytes from a source array starting at a particular offset to a destination array starting at a particular offset. This is the best option in terms of speed since it directly accesses the underlying memory.

Download  Run Code

5. Using For Loop

Finally, you can write a custom routine for copying an array. The idea is to allocate space for the destination array and copy each element from the source array to the destination array using a standard for-loop.

Download  Run Code

That’s all about creating a copy of an array in C#.