EN
C# / .NET - clone array
3
points
In this article, we would like to show you how to clone array in C#.
Quick solution:
int[] array = new int[] { 1, 2, 3 };
int[] clone = (int[]) array.Clone();
Warning: the above solution do not create deep copy (it makes copy on first lavel only).
Practical example
In this example, we use Clone() method to make a copy of the existing array.
using System;
public class TestClass
{
public static void Main()
{
int[] array = new int[] { 1, 2, 3 };
int[] clone = (int[]) array.Clone();
Console.WriteLine("Input array elements:");
foreach (int item in array)
Console.WriteLine(item);
Console.WriteLine("Clone array elements:");
foreach (int item in clone)
Console.WriteLine(item);
}
}
Output:
Input array elements:
1
2
3
Clone array elements:
1
2
3