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

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

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...