TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# List CopyTo Method

This C# program uses the CopyTo method on the List type. It creates 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.

Int Array

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

Console.WriteLine

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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf