How to clone an Array in C#
The Array class in the System namespace provides the Clone() method, which can be used to do a shallow copy of the array elements.
Syntax
public object Clone ();
- This method performs a shallow copy of the array elements. If the array contains object references, those references are copied, but the actual objects that the references refer to are not.
- The cloned array is of the type of the original array.
- The time complexity of this method is O(n), where n is the number of elements in the array.
In the below code, we have created and initialized an integer array. We first print the original array and then perfrom a shallow copy of the array using the Array.Clone() method.
After that, we print the cloned array contents.
The program prints the below output and exits.
Original Array : 10,13,15,18,23
Cloned Array : 10,13,15,18,23
using System;class ArrayClone{static void Main(){int[] numArray = {10,13,15,18,23};Console.WriteLine("Original Array : {0}", string.Join(",",numArray));int[] clonedNumArray = (int[])numArray.Clone();Console.WriteLine("Cloned Array : {0}", string.Join(",",clonedNumArray));}}