CopyTo
This C# method copies List
elements to an array. It provides a way to do this in one declarative function call—this keeps code simpler.
When using the CopyTo()
method, we must make sure the target array is properly allocated. And the element types must match.
To begin, we have a List
of ints and we call its CopyTo
method with an index argument. Copying begins in the array at the argument index.
List
at its start, but into the array at the specified index.using System; using System.Collections.Generic; var list = new List<int>() { 10, 20, 30 }; int[] array = new int[5]; // Use CopyTo to copy into an array starting at a certain index. // .. The entire list is copied. list.CopyTo(array, 2); Console.WriteLine("LIST: " + string.Join(",", list)); Console.WriteLine("ARRAY: " + string.Join(",", array));LIST: 10,20,30 ARRAY: 0,0,10,20,30
This program creates a List
with three elements in it: the values 5, 6 and 7. Next an int
array is allocated. It has a length equal to the Count
of the List
.
CopyTo
method is invoked upon the list variable. The array now contains all the elements of the originating List
.using System; using System.Collections.Generic; // Create a list with 3 elements. var list = new List<int>() { 5, 6, 7 }; // Create an array with length of 3. int[] array = new int[list.Count]; // Copy the list to the array. list.CopyTo(array); // Display. Console.WriteLine(array[0]); Console.WriteLine(array[1]); Console.WriteLine(array[2]);5 6 7
CopyTo()
calls Array.Copy
on the internal array inside the List
. Examining the secrets inside .NET implementations helps us learn good practices.
The List
CopyTo
method provides a way to copy all the elements of a List
to a compatible and allocated array. The array must have adequate space for all the elements.
The type of the elements in the array must be equivalent to the type of the List
elements. Our code must have a correct target array.