How to copy a range of elements of an array to another in C# ?

If you want to copy one array to another in C#, you can use the Array.Copy static method . The Array.Copy method provides additional options for the developers to copy just the part of an array or range to another by specifying the start index of both the source and the destination array as well as the number of elements to copy.

How to copy a range of elements of an array to another in C# ?

Below is an example demonstrating the usage of Array.Copy to copy the 3nd and the 4rd element from the source array to the destination.

using System;
using System.Collections.Generic;
using System.Linq;

namespace DeveloperPublishConsoleApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string[] inputStr = { "Java", "CSharp", "Xamarin", "Windows", "android", "iOS" };
            Console.WriteLine("Input Array");
            Console.WriteLine("----------");
            foreach (string input in inputStr)
            {
                Console.WriteLine(input);
            }
            string[] outputArray = new string[10];
        // Copy array from source to destination
            Array.Copy(inputStr, 2, outputArray, 0, 2);

            Console.WriteLine("Copied Array");
            Console.WriteLine("-----------");
            foreach (string input in outputArray)
            {
                Console.WriteLine(input);
            }

            Console.ReadLine();
        }
    }
}


In the above code snippet , following is the code that copies the source array to destination

Array.Copy(inputStr, 2, outputArray, 0, 2);

inputStr = source array
2 = start index in the source array
outputArray  destination array
0 = start index in the destination array
2 = number of elements to copy.

Output

image

Leave A Reply

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

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...