Array copy

In this chapter you will learn:

  1. How to copy an array to another array
  2. How to copy elements to another array
  3. Copy into middle of target

Copy an array

using System;//from j  a  v  a 2  s. com


public class MainClass
{

    public static void Main()
    {
        int[] srcArray = new int[] { 1, 2, 3 };
        int[] destArray = new int[] { 4, 5, 6, 7, 8, 9 };

        Array.Copy(srcArray, destArray, srcArray.Length);
        srcArray.CopyTo(destArray, 0);
        srcArray.CopyTo(destArray, 3);
        Array.Copy(srcArray, 0, destArray, 2, srcArray.Length);

    }
}

Copy elements to another array

using System;  //from  jav a  2s .  c o m
  
class MainClass {     
  public static void Main() {     
    int[] source = { 21, 22, 23, 24, 25 }; 
    int[] target = { 11, 12, 13, 14, 15 }; 
    int[] source2 = { -1, -2, -3, -4, -5 }; 
 
    Array.Copy(source, target, source.Length); 
 

    Console.Write("target after copy:  "); 
    foreach(int i in target){
      Console.Write(i + " ");
    }   
    Console.WriteLine(); 
  } 
}

The code above generates the following result.

Copy into middle of target

The following code shows how to copy to the middle of another array.

using System;  // j av a2s  .  c o m
  
class MainClass {     
  public static void Main() {     
    int[] source = { 1, 2, 3, 4, 5 }; 
    int[] target = { 11, 12, 13, 14, 15 }; 
    int[] source2 = { -1, -2, -3, -4, -5 }; 
 
    Array.Copy(source2, 2, target, 3, 2); 
 
    Console.Write("target after copy:  "); 
    foreach(int i in target)  
      Console.Write(i + " "); 
    Console.WriteLine(); 
 
  } 
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to clone an array with reference data
  2. How to clone value array
Home » C# Tutorial » Array
Array
Array loop
Array dimension
Jagged Array
Array length
Array Index
Array rank
Array foreach loop
Array ForEach Action
Array lowerbound and upperbound
Array Sort
Array search with IndexOf methods
Array binary search
Array copy
Array clone
Array reverse
Array ConvertAll action
Array Find
Array SequenceEqual