Languages
[Edit]
EN

C# / .NET - clone array

3 points
Created by:
Dharman
518

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join