TheDeveloperBlog.com


C# ToList Extension Method

ToList converts collections to List instances. It is a fast and easy-to-remember method. It returns a List instance with the appropriate elements. It creates a new List internally, with the List constructor.


Example. First, this program creates an array with an array initializer. It then converts that object data into a List instance. The System.Linq namespace is included. This allows us to invoke the ToList extension method on the array reference.

Based on:

.NET 4.5

C# program that uses ToList extension method

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
	//
	// Use this input string[] array.
	// ... Convert it to a List with the ToList extension.
	//
	string[] array = new string[]
	{
	    "A",
	    "B",
	    "C",
	    "D"
	};
	List<string> list = array.ToList();
	//
	// Display the list.
	//
	Console.WriteLine(list.Count);
	foreach (string value in list)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

4
A
B
C
D

This program introduces the Main entry point, and in the method body an array is allocated. It uses an array initializer to specify that the array has four elements. The values in this string array are specified.

Array InitializersArrays

Next: The ToList extension method is called on that array reference. ToList is an extension method from the System.Linq namespace.

Extension Method

And: It is called in the same way as an instance method is called. It returns a new List of string instances.

StringsConsole.WriteLine

Internals. The ToList method internally checks its parameter for null, which will occur if you try to use ToList on a null reference. It then invokes the List type constructor with the instance parameter.

Null

This means that using "instance.ToList()" is equivalent to using "new List<T>(instance)" where T is the type. The ToList extension method just calls the List constructor. The JIT compiler will inline simple method calls.

ConstructorJIT

Summary. We examined the ToList extension method. We noted its usage in a trivial program and also its implementation. Internally the ToList extension method invokes the List type constructor. Its performance characteristics are about the same.