C# List ToArray example

In this source code example, we will demonstrate how to convert a List to an Array in C#.

The ToArray method copies the elements of a list into an array.

C# List ToArray example 1

In the example, we create an array from a list. We print the type of both containers with GetType.
using System;
using System.Collections.Generic;

public class ListDemo
{
    public static void Main(string[] args)
    {
        var fruits = new List<string> { "banana", "mango", "apple", "watermelon" };

        Console.WriteLine(fruits.GetType());
        
        var fruits2 = fruits.ToArray();
        Console.WriteLine(fruits2.GetType());
        
        foreach(string f in fruits2) {

            Console.WriteLine(f);
        }
    }
}

Output:

System.Collections.Generic.List`1[System.String]
System.String[]
banana
mango
apple
watermelon

C# List ToArray example 2

The following example converts a List of an integer into an array of integers:
using System;
using System.Collections.Generic;

public class ListDemo
{
    public static void Main(string[] args)
    {
        var nums = new List<int> { 10, 20, 30, 40, 50 };
        
        Console.WriteLine(nums.GetType());
        
        int[] nums2 = nums.ToArray();
        Console.WriteLine(nums2.GetType());
        
        foreach(int e in nums) {

            Console.WriteLine(e);
        }
    }
}

Output:

System.Collections.Generic.List`1[System.Int32]
System.Int32[]
10
20
30
40
50

Related C# List Examples


Comments