C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Step 1: We create a List and populate it with some strings. The List here can only hold strings (or null).
ListStep 2: Next we use ToArray on the List. To test it, we pass the string array to the Test() method.
ToArrayArrayC# program that converts List to array
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Step 1: create list.
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
list.Add("four");
list.Add("five");
// Step 2: convert to string array.
string[] array = list.ToArray();
Test(array);
}
static void Test(string[] array)
{
Console.WriteLine("Array received: " + array.Length);
}
}
Output
Array received: 5
Part 1: Here we initialize a new string array containing 5 strings. These are specified as string literals.
Part 2: Here we convert the array to a List with the List constructor. This returns a new List of strings.
Part 3: Here the example converts the array to a List with the ToList() instance method.
C# program that uses List constructor and ToList
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Part 1: string array.
string[] array = new string[]
{
"one",
"two",
"three",
"four",
"five"
};
// Part 2: use list constructor.
List<string> list1 = new List<string>(array);
Test(list1);
// Part 3: use ToList method.
List<string> list2 = array.ToList();
Test(list2);
}
static void Test(List<string> list)
{
Console.WriteLine("List count: " + list.Count);
}
}
Output
List count: 5
List count: 5
So: That means parts 2 and 3 above are the same except for a check against the null literal.
IL Disassembler TutorialNote: If your code statement tries to assign a List to an array, you will get this error.
Performance: I have not performed extensive micro-benchmarks on these conversion methods.
Note: The new List constructor would be the fastest for that example. A loop that copies elements would be similar.