C# .Copy()
The .Copy() method in C# copies a range of elements from one array to another array.
Syntax
Array.Copy(sourceArray, destinationArray, length);
Array.Copy(sourceArray, sourceStartingIndex, destinationArray, destinationStartingIndex, length);
.Copy() is a static method of the Array object. It takes the following arguments:
sourceArrayis copied, starting from the first element of the array.destinationArrayis where thesourceArrayis copied to.lengthis specified as an integer and determines how many elements are copied from the source to the destination array.
It is also possible to overload this method with two additional parameters:
sourceStartingIndexis the index where the source array’s elements are first copied from.destinationStartingIndexis the destination array’s index to which the elements from the source array are copied to.
Example
The following example initializes the array sourceArray and the array destinationArray. Using a foreach loop, the contents of destinationArray are printed to the console:
using System;public class Example{public static void Main(string[] args){string[] sourceArray = new string[] { "red", "orange", "yellow", "green", "blue", "indigo", "violet"};string[] destinationArray = new string[sourceArray.Length];// sourceArray.Length returns the integer for the third parameter, length.Array.Copy(sourceArray, destinationArray, sourceArray.Length);foreach (string element in destinationArray){Console.Write($"{element} ");}}}
This is what is printed to the console:
red orange yellow green blue indigo violet
Codebyte Example
The following codebyte is runnable and shows one of the several overload functions with the Array.Copy() method. In this example, sourceArray is copied starting from the third element in the array [2]and stores elements [2], [3], [4] starting as the first element in destinationArray. The remaining elements return 0:
Learn C# on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.
- Beginner Friendly.15 hours