SoFunction
Updated on 2025-03-06

Methods for array initialization and array element copying in C#

This article describes the methods of array initialization and array element copying in C#. Share it for your reference. The details are as follows:

The following code demonstrates how to create and initialize an array, and how to copy array elements from one to another in C#.

using System; 
public class ArraySample
{
 public static void Main()
 {
   // Create and initialize arrays   int[] intArr = new int[5] {1,2,3,4,5};
   Object[] objArr = new Object[5] {10,20,30,40,50};
   foreach (int i in intArr)
   {
   (i);
   (",");
   }
   ();
   foreach (Object i in objArr )
   {
    (i);
    (",");
   }
   ();
   // Copy the first three elements of intArr to objArr   (intArr, objArr,3);
   ("After coping" );
   foreach (int i in intArr)
   {
   (i);
   (" , ");
   }
   ( );
   foreach (Object i in objArr)
   {
   (i);
   (" ,");
   }
   ( );
 }
}

The output results of the code running are as follows:

1,2,3,4,5,
10,20,30,40,50,
After coping
1 , 2 , 3 , 4 , 5 ,
1 ,2 ,3 ,40 ,50 ,

I hope this article will be helpful to everyone's C# programming.