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.
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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 11, 2023 (edit).