How To Copy An Array In C#

Introduction 

In this article, you will learn that the Array is a collection of similar data types stored in contiguous memory locations. It is a proper data structure that allows you to store and manipulate values of the same type. You will learn copy array method used to copy a section of one Array to another array in C#, and it performs type casting and boxing as required to data in C#.

To create an array in C#, you need to specify the data type of the array elements and the number of elements it can hold. Here's an example of how to declare an integer array that can have five elements,

int[] myArray = new int[5];

This creates an array called myArray that can hold five integers. You can also initialize the Array with values like this.

Copy An Array In CSharp

Methods to copy an array in C#

  • Using the ArrayCopy() 
  • Using the Clone() 
  • Using the CopyTo() 

Method 1. Using the ArrayCopy()

The array copy method copies all the current array elements to the specified destination array in C#. This method should be called from the source array and takes two parameters. The first is the Array you want to copy to, and the second parameter tells it what index of the destination array it should start copying into in C#  

public class ArrayDemo {
    public static void Main() {
        int[] n = new int[10]; /* n is an array of 10 integers */
        int[] m = new int[5]; /* m is an array of 5 integers */
        for (int i = 0; i < 10; i++) {
            n[i] = i + 200;
        }
        Console.WriteLine("Original Array...");
        foreach(int j in n) {
            int i = j - 200;
            Console.WriteLine("Element[{0}] = {1}", i, j);
        }
        Array.Copy(n, 0, m, 0, 5);
        Console.WriteLine("New Array...");
        foreach(int res in m) {
            Console.WriteLine(res);
        }
        Console.ReadKey();
    }
}

This statement is declared two integer arrays: n With a length of 10 and m size of 5. Using a loop, it fills the

Array with values ranging from 200 to 209. After filling the n The code prints out the original Array by looping through each element of the Array using a foreach loop. It subtracts 200 from each value and displays the index and value of the array element.

Next, the code uses the Array.Copy method to copy the first five elements of the n Array to the m Array. The Array.Copy method takes the source array (n), the starting index in the source array (0), the destination array (m), the starting index in the destination array (0), and the number of elements to copy (5). Finally, the code prints out the Array's contents using a foreach loop without subtracting 200 from the values.

When run, the output of the program will be  

Method 2. Using the Clone()

The Array class provides a Clone method allowing you to create a new array with the same contents as an existing one. Here's an example of how to use the Clone method:  

   public static void Main()
            {
            int[] originalArray = { 1, 2, 3, 4, 5 };

            // create a new array using the Clone method
            int[] clonedArray = (int[])originalArray.Clone();

            // print the original array
            Console.WriteLine("Original array:");
            PrintArray(originalArray);

            // print the cloned array
            Console.WriteLine("Cloned array:");
            PrintArray(clonedArray);

            // modify an element in the original array
            originalArray[0] = 100;

            // print the original array again
            Console.WriteLine("Modified original array:");
            PrintArray(originalArray);

            // print the cloned array again
            Console.WriteLine("Cloned array after modifying original array:");
            PrintArray(clonedArray);

            Console.ReadLine();
        }

        // helper method to print an array
        static void PrintArray(int[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i] + " ");
            }
            Console.WriteLine();
        }
    }
}

This program creates an array of integers called originalArray, then a new array called clonedArray using the Clone method. It then prints both arrays to the console using a helper method called PrintArray.

After that, it modifies an element in the original Array and prints both arrays again to demonstrate that changing the original Array does not affect the cloned Array.

Output  

Method 3. Using the CopyTo()

This method arranges Demo class copies of all the Array data to an existing array. It performs a shallow copy in C#. This is used to copy a one-dimensional array in C#. This statement copies the complete content of the Array to the new Array starting from the index passed in the parameter to C#.

This statement is the CopyTo method of the Array class name. 

Array.CopyTo(destArray, index);
  • The Array is the Array we want to copy the contents
  • destArray is the Name of the Array of the same data type as the Array where the content will be copied to
  • the index is the integer from where you want to start copying on destArray

The following example is copying array data to a new array using the CopyTo() method in C#. 

public class ArrayDemo {
    public static void Main() {
        var array1 = new [] {
            "Ravi",
            "Rahul",
            "Nitin",
            "Welcomes",
            "You"
        };
        var array2 = new string[10];
        array2[0] = "Narveer";
        // cloning arr and storing it in new array
        array1.CopyTo(array2, 1);
        // Printing array using loop
        foreach(var element in array2) {
            System.Console.WriteLine(element);
        }
    }
}

This statement is that demonstrates the use of arrays in C#. The program creates two arrays, array1 and array2. The first Array, array1, is initialized with string values. The second Array, array2, is declared with a size of 10 but is not initialized with any values except for the first element, which is assigned the "Narveer."

The program then uses the CopyTo method to copy the elements from array1 to array2 starting from the second index (index 1). This method takes two arguments: the destination array and the starting index.

Finally, the program prints the elements of array2 using a foreach loop. The loop iterates through each element in the Array and prints it to the console.

When executed, the output of this program will be

Narveer Ravi Rahul Nitin Welcomes You

Note that the elements of array1 are copied to array2 starting from index 1, so the first element of array2 ("Narveer") is not overwritten.

Output  

How to Copy an Array in C#

Conclusion   

In this article, you will learn how to copy an array in C#. We have discussed different ways to copy arrays in C#. Understanding these methods will help you to write efficient and error-free code. Working with Arrays in C# (code included) check out- Working with Arrays in C# (code included)

FAQs  

Q: Can you explain the difference between shallow and deep copies of an array in C#?

A: When you copy an array in C#, you can make two types of copies: shallow and deep.

A shallow copy of an array creates a new array with the same elements as the original Array. Still, the elements in the new Array reference the same objects as those in the original Array. In other words, a shallow copy creates a new array that points to the same objects as the original Array.

On the other hand, a deep copy of an array creates a new array with the same elements as the original Array, but the elements in the new Array are copies of the objects in the original Array. In other words, a deep copy creates a new array with its copies of the objects in the original Array.

To make a shallow copy of an array in C#, you can use the Array.Clone() method. To make a deep copy, you must manually create a new array and copy each element from the original Array to the new Array, starting new instances of each object.

Understanding the difference between shallow and deep copies is essential when working with arrays and objects in C#. Depending on your needs, you may want to use a shallow or deep copy to avoid unintended consequences.   

Q: How do you copy an array in C#?

A:  You can copy an array using the Array.Copy() method or assign the source array to a new destination array.


Similar Articles