C# List CopyTo (Copy List Elements to Array)

Use the CopyTo method on the List type to copy a List to an array.
CopyTo copies List elements to an array. This method provides a way to do this in one declarative function call. When using the CopyTo method, you must make sure the array is properly allocated.
Example. To start, 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. Third the CopyTo method is invoked upon the list variable.ListInt Array

Finally: We prove that the array now contains all the elements of the originating List.

C# program that uses CopyTo on List using System; using System.Collections.Generic; class Program { static void Main() { // Create a list with three elements. var list = new List<int>() { 5, 6, 7 }; // Create an array with length of three. 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]); } } Output 5 6 7
Internals. What does the .NET Framework use to copy the elements in CopyTo? It eventually uses Array.Copy on the internal array inside the List. Examining the secrets inside the .NET Framework implementations helps us learn good practices.Array.Copy

Note: The .NET Framework developers probably know more about the best way to do things than do most of us.

Summary. The List CopyTo method provides a way to declaratively and easily copy all the elements of a List to a compatible and allocated array. The array must have adequate space for all the elements to be accommodated.

Also: The type of the elements in the array must be equivalent to the type of the List elements as well.

Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to