Home
C#
List CopyTo Examples
Updated Oct 11, 2023
Dot Net Perls
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.
Method notes. When using the CopyTo() method, we must make sure the target array is properly allocated. And the element types must match.
List
Complex example. 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.
Important With this overload, we copy from the 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
Simple example. 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.
int Array
Info The 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
Internals. CopyTo() calls Array.Copy on the internal array inside the List. Examining the secrets inside .NET implementations helps us learn good practices.
Array.Copy
Note The .NET 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 copy all the elements of a List to a compatible and allocated array. The array must have adequate space for all the elements.
Elements, review. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 11, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen