Copy one array in another

To copy one array in anthor in C#, we can use the Clone() function of Array class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] myarray1= { 10, 20, 30 };
            int[] myarray2 = (int[])myarray1.Clone();

            Console.WriteLine("\nArray1");
            foreach (int item in myarray1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine("\nArray2");
            foreach (int item in myarray2)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();

            myarray2[1] = 4000;

            Console.WriteLine("\nArray1");
            foreach (int item in myarray1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine("\nArray2");
            foreach (int item in myarray2)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();




        }
    }
}

 

Add a Comment

Your email address will not be published. Required fields are marked *