Array copy
In this chapter you will learn:
- How to copy an array to another array
- How to copy elements to another array
- 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:
Home » C# Tutorial » Array