Copying Arrays in C#

Arrays offer very rich functionality in terms of methods and properties to perform higher level tasks. In this article, we going to see about very popular and important method in Arrays.

Array implements many methods and properties itself, so that we can do copying the array, rearranging the elements in it and finding particular elements. As like other collections, array also picks up a lot of extension methods from LINQ.

Array offers a three significant ways to copy the elements. They are

  1. CopyTo
  2. Array.copy()
  3. ToArray()

Let’s discuss how to use these features one by one, so that we can improve our code productivity.

1.CopyTo

public void CopyTo(Array arr, long index);

CopyTo method allows us to copying the array elements into a new array. This CopyTo method won’t return any type. It is a void type.


When I do a reference check of these arrays,  
if(originalArray == destArray)
{
   Console.WriteLine("Both the arrays are referring to same memory");
}
else
{
   Console.WriteLine("Both the arrays are not referring        to same memory");
}
When i run this program, I got the else condition execution. Because, even though array values may be equal, it won't refer to the same location while copying.

2. Array.copy()

This is the static method in C#. It has several overload methods. It gives the more flexibility than copyTo method to the users.

public static void Copy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length);

Even though Array.Copy() and CopyTo() method, performs well, but it reduces code readability. Let us see the third way of copying array elements.

3. ToArray()

The third way of copying array elements by using ToArray() method. This is the common method, most of the developers prefers to use this method. It improves the readability. This method is coming from LINQ. It is one of the LINQ extension method. It is very simple to use in code.

int[] destArray = originalArray.ToArray();

These above are three significant ways of copying the arrays in C#. I basically prefer third way of copying the array elements, because it very easy and improves the readability also.

Thanks for reading, If you like this article, please share with your friends.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s