C# - Produce a Third Array by Appending Two Arrays

Here, we are going to learn how to produce a third array by appending two different arrays in C#?
Submitted by Nidhi, on August 22, 2020

Here we will create three integer arrays and then copy array1 to array3 and then append array2 to the array3 then we will get the final result in array3. Here we will use BlockCopy() method to copy one array to another.

C# program to produce a third array by appending two different arrays

The source code to produce a third array by appending two different arrays in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to produce a third array by 
//appending two different arrays in C#.

using System;

class Demo
{
    static void Main()
    {
        int[] intArr1   = {1,2,3,4,5};
        int[] intArr2   = {6,7,8,9,0};
        int[] intArr3   = new int[10];

        int totalLengthInBytes = 0;

        totalLengthInBytes = intArr1.Length * sizeof(int);
        Buffer.BlockCopy(intArr1, 0, intArr3, 0, totalLengthInBytes);

        totalLengthInBytes = intArr2.Length * sizeof(int);
        Buffer.BlockCopy(intArr2, 0, intArr3, totalLengthInBytes, totalLengthInBytes);

        foreach (int items in intArr3)
        {
            Console.Write(items+ " ");
        }
        Console.WriteLine();
    }
}

Output

1 2 3 4 5 6 7 8 9 0
Press any key to continue . . .

Explanation

In the above program, we created three arrays intArray1, intArray2, and intArray3. The intArray1 and intArray2 contain 5 items and we occupied space of 10 items for intArray3.

int totalLengthInBytes = 0;

totalLengthInBytes = intArr1.Length * sizeof(int);
Buffer.BlockCopy(intArr1, 0, intArr3, 0, totalLengthInBytes);

totalLengthInBytes = intArr2.Length * sizeof(int);
Buffer.BlockCopy(intArr2, 0, intArr3, totalLengthInBytes, totalLengthInBytes);

In the above code, we copied intArray1 to intArray3 and then appended intArray2 into intArray3 using BlockCopy() method.

foreach (int items in intArr3)
{
    Console.Write(items+ " ");
}

The above code will print all elements of intArray3 on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.