Edit

Share via


List<T> Constructors

Definition

Initializes a new instance of the List<T> class.

Overloads

List<T>()

Initializes a new instance of the List<T> class that is empty and has the default initial capacity.

List<T>(IEnumerable<T>)

Initializes a new instance of the List<T> class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied.

List<T>(Int32)

Initializes a new instance of the List<T> class that is empty and has the specified initial capacity.

List<T>()

Source:
List.cs
Source:
List.cs
Source:
List.cs
Source:
List.cs

Initializes a new instance of the List<T> class that is empty and has the default initial capacity.

public:
 List();
public List();
Public Sub New ()

Examples

The following example demonstrates the parameterless constructor of the List<T> generic class. The parameterless constructor creates a list with the default capacity, as demonstrated by displaying the Capacity property.

The example adds, inserts, and removes items, showing how the capacity changes as these methods are used.

List<string> dinosaurs = new List<string>();

Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);

dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
    Console.WriteLine(dinosaur);
}

Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);

Console.WriteLine("\nContains(\"Deinonychus\"): {0}",
    dinosaurs.Contains("Deinonychus"));

Console.WriteLine("\nInsert(2, \"Compsognathus\")");
dinosaurs.Insert(2, "Compsognathus");

Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
    Console.WriteLine(dinosaur);
}

// Shows accessing the list using the Item property.
Console.WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]);

Console.WriteLine("\nRemove(\"Compsognathus\")");
dinosaurs.Remove("Compsognathus");

Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
    Console.WriteLine(dinosaur);
}

dinosaurs.TrimExcess();
Console.WriteLine("\nTrimExcess()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);

dinosaurs.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);

/* This code example produces the following output:

Capacity: 0

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus

Capacity: 8
Count: 5

Contains("Deinonychus"): True

Insert(2, "Compsognathus")

Tyrannosaurus
Amargasaurus
Compsognathus
Mamenchisaurus
Deinonychus
Compsognathus

dinosaurs[3]: Mamenchisaurus

Remove("Compsognathus")

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus

TrimExcess()
Capacity: 5
Count: 5

Clear()
Capacity: 5
Count: 0
 */
Imports System.Collections.Generic

Partial Public Class Program
    Public Shared Sub ShowPlanets()
        Dim planets As New List(Of String)

        Console.WriteLine(vbLf & "Capacity: {0}", planets.Capacity)

        planets.Add("Mercury")
        planets.Add("Venus")
        planets.Add("Earth")
        planets.Add("Mars")
        planets.Add("Jupiter")

        Console.WriteLine()
        For Each planet As String In planets
            Console.WriteLine(planet)
        Next

        Console.WriteLine(vbLf & "Capacity: {0}", planets.Capacity)
        Console.WriteLine("Count: {0}", planets.Count)

        Console.WriteLine(vbLf & "Contains(""Mars""): {0}", _
            planets.Contains("Mars"))

        Console.WriteLine(vbLf & "Insert(2, ""Saturn"")")
        planets.Insert(2, "Saturn")

        Console.WriteLine()
        For Each planet As String In planets
            Console.WriteLine(planet)
        Next
        ' Shows how to access the list using the Item property.
        Console.WriteLine(vbLf & "planets(3): {0}", planets(3))
        Console.WriteLine(vbLf & "Remove(""Jupiter"")")
        planets.Remove("Jupiter")

        Console.WriteLine()
        For Each planet As String In planets
            Console.WriteLine(planet)
        Next

        planets.TrimExcess()
        Console.WriteLine(vbLf & "TrimExcess()")
        Console.WriteLine("Capacity: {0}", planets.Capacity)
        Console.WriteLine("Count: {0}", planets.Count)

        planets.Clear()
        Console.WriteLine(vbLf & "Clear()")
        Console.WriteLine("Capacity: {0}", planets.Capacity)
        Console.WriteLine("Count: {0}", planets.Count)
    End Sub
End Class

' This code example produces the following output:
'
' Capacity: 0
'
' Mercury
' Venus
' Earth
' Mars
' Jupiter
'
' Capacity: 8
' Count: 5
'
' Contains("Mars"): True
'
' Insert(2, "Saturn")
'
' Mercury
' Venus
' Saturn
' Earth
' Mars
' Jupiter
'
' planets(3): Earth
'
' Remove("Jupiter")
'
' Mercury
' Venus
' Saturn
' Earth
' Mars
'
' TrimExcess()
' Capacity: 5
' Count: 5
'
' Clear()
' Capacity: 5
' Count: 0

[<EntryPoint>]
let main argv = 
    // We refer to System.Collections.Generic.List<'T> by its type 
    // abbreviation ResizeArray<'T> to avoid conflict with the List module.    
    // Note: In F# code, F# linked lists are usually preferred over
    // ResizeArray<'T> when an extendable collection is required.
    let dinosaurs = ResizeArray<_>()
 
    // Write out the dinosaurs in the ResizeArray.
    let printDinosaurs() =
        printfn ""
        dinosaurs |> Seq.iter (fun p -> printfn "%O" p) 
 
    
    printfn "\nCapacity: %i" dinosaurs.Capacity
 
    dinosaurs.Add("Tyrannosaurus")
    dinosaurs.Add("Amargasaurus")
    dinosaurs.Add("Mamenchisaurus")
    dinosaurs.Add("Deinonychus")
    dinosaurs.Add("Compsognathus")
 
    printDinosaurs()
 
    printfn "\nCapacity: %i" dinosaurs.Capacity
    printfn "Count: %i" dinosaurs.Count
 
    printfn "\nContains(\"Deinonychus\"): %b" (dinosaurs.Contains("Deinonychus"))
 
    printfn "\nInsert(2, \"Compsognathus\")"
    dinosaurs.Insert(2, "Compsognathus")
 
    printDinosaurs()
 
    // Shows accessing the list using the Item property.
    printfn "\ndinosaurs[3]: %s" dinosaurs.[3]
 
    printfn "\nRemove(\"Compsognathus\")"
    dinosaurs.Remove("Compsognathus") |> ignore
 
    printDinosaurs()
 
    dinosaurs.TrimExcess()
    printfn "\nTrimExcess()"
    printfn "Capacity: %i" dinosaurs.Capacity
    printfn "Count: %i" dinosaurs.Count
 
    dinosaurs.Clear()
    printfn "\nClear()"
    printfn "Capacity: %i" dinosaurs.Capacity
    printfn "Count: %i" dinosaurs.Count
 
    0 // return an integer exit code
 
    (* This code example produces the following output:
 
Capacity: 0
 
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
 
Capacity: 8
Count: 5
 
Contains("Deinonychus"): true
 
Insert(2, "Compsognathus")
 
Tyrannosaurus
Amargasaurus
Compsognathus
Mamenchisaurus
Deinonychus
Compsognathus
 
dinosaurs[3]: Mamenchisaurus
 
Remove("Compsognathus")
 
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
 
TrimExcess()
Capacity: 5
Count: 5
 
Clear()
Capacity: 5
Count: 0
    *)

Remarks

The capacity of a List<T> is the number of elements that the List<T> can hold. As elements are added to a List<T>, the capacity is automatically increased as required by reallocating the internal array.

If the size of the collection can be estimated, using the List<T>(Int32) constructor and specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the List<T>.

The capacity can be decreased by calling the TrimExcess method or by setting the Capacity property explicitly. Decreasing the capacity reallocates memory and copies all the elements in the List<T>.

This constructor is an O(1) operation.

Applies to

List<T>(IEnumerable<T>)

Source:
List.cs
Source:
List.cs
Source:
List.cs
Source:
List.cs

Initializes a new instance of the List<T> class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied.

public:
 List(System::Collections::Generic::IEnumerable<T> ^ collection);
public List(System.Collections.Generic.IEnumerable<T> collection);
new System.Collections.Generic.List<'T> : seq<'T> -> System.Collections.Generic.List<'T>
Public Sub New (collection As IEnumerable(Of T))

Parameters

collection
IEnumerable<T>

The collection whose elements are copied to the new list.

Exceptions

collection is null.

Examples

The following example demonstrates the List<T> constructor and various methods of the List<T> class that act on ranges. An array of strings is created and passed to the constructor, populating the list with the elements of the array. The Capacity property is then displayed, to show that the initial capacity is exactly what is required to hold the input elements.

using System;
using System.Collections.Generic;

string[] input = { "Apple",
                   "Banana",
                   "Orange" };

List<string> fruits = new List<string>(input);

Console.WriteLine("\nCapacity: {0}", fruits.Capacity);
Console.WriteLine();

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Console.WriteLine("\nAddRange(fruits)");
fruits.AddRange(fruits);

Console.WriteLine();
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Console.WriteLine("\nRemoveRange(2, 2)");
fruits.RemoveRange(2, 2);

Console.WriteLine();
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

input = new string[] { "Mango",
                       "Pineapple",
                       "Watermelon" };

Console.WriteLine("\nInsertRange(3, input)");
fruits.InsertRange(3, input);

Console.WriteLine();
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Console.WriteLine("\noutput = fruits.GetRange(2, 3).ToArray()");
string[] output = fruits.GetRange(2, 3).ToArray();

Console.WriteLine();
foreach (string fruit in output)
{
    Console.WriteLine(fruit);
}

/*
    This code example produces the following output:

    Capacity: 3

    Apple
    Banana
    Orange

    AddRange(fruits)

    Apple
    Banana
    Orange
    Apple
    Banana
    Orange

    RemoveRange(2, 2)

    Apple
    Banana
    Banana
    Orange

    InsertRange(3, input)

    Apple
    Banana
    Banana
    Mango
    Pineapple
    Watermelon
    Orange

    output = fruits.GetRange(2, 3).ToArray()

    Banana
    Mango
    Pineapple
*/
Imports System.Collections.Generic

Partial Public Class Program
    Public Shared Sub ShowFruits()

        Dim input() As String = { "Apple", _
                                  "Banana", _
                                  "Orange" }

        Dim fruits As New List(Of String)(input)

        Console.WriteLine(vbLf & "Capacity: {0}", fruits.Capacity)
        Console.WriteLine()

        For Each fruit As String In fruits
            Console.WriteLine(fruit)
        Next

        Console.WriteLine(vbLf & "AddRange(fruits)")
        fruits.AddRange(fruits)

        Console.WriteLine()
        For Each fruit As String In fruits
            Console.WriteLine(fruit)
        Next

        Console.WriteLine(vbLf & "RemoveRange(2, 2)")
        fruits.RemoveRange(2, 2)

        Console.WriteLine()
        For Each fruit As String In fruits
            Console.WriteLine(fruit)
        Next

        input = New String() { "Mango", _
                               "Pineapple", _
                               "Watermelon" }

        Console.WriteLine(vbLf & "InsertRange(3, input)")
        fruits.InsertRange(3, input)

        Console.WriteLine()
        For Each fruit As String In fruits
            Console.WriteLine(fruit)
        Next

        Console.WriteLine(vbLf & "output = fruits.GetRange(2, 3).ToArray")
        Dim output() As String = fruits.GetRange(2, 3).ToArray()

        Console.WriteLine()
        For Each fruit As String In output
            Console.WriteLine(fruit)
        Next

    End Sub
End Class

' This code example produces the following output:
'
' Capacity: 3
'
' Apple
' Banana
' Orange
'
' AddRange(fruits)
'
' Apple
' Banana
' Orange
' Apple
' Banana
' Orange
'
' RemoveRange(2, 2)
'
' Apple
' Banana
' Banana
' Orange
'
' InsertRange(3, input)
'
' Apple
' Banana
' Banana
' Mango
' Pineapple
' Watermelon
' Orange
'
' output = fruits.GetRange(2, 3).ToArray
'
' Banana
' Mango
' Pineapple

Remarks

The elements are copied onto the List<T> in the same order they are read by the enumerator of the collection.

This constructor is an O(n) operation, where n is the number of elements in collection.

See also

Applies to

List<T>(Int32)

Source:
List.cs
Source:
List.cs
Source:
List.cs
Source:
List.cs

Initializes a new instance of the List<T> class that is empty and has the specified initial capacity.

public:
 List(int capacity);
public List(int capacity);
new System.Collections.Generic.List<'T> : int -> System.Collections.Generic.List<'T>
Public Sub New (capacity As Integer)

Parameters

capacity
Int32

The number of elements that the new list can initially store.

Exceptions

capacity is less than 0.

Examples

The following example demonstrates the List<T>(Int32) constructor. A List<T> of strings with a capacity of 4 is created, because the ultimate size of the list is known to be exactly 4. The list is populated with four strings, and a read-only copy is created by using the AsReadOnly method.

using System;
using System.Collections.Generic;

public partial class Program
{
    public static void Main()
    {
        List<string> animals = new List<string>(4);

        Console.WriteLine("\nCapacity: {0}", animals.Capacity);

        animals.Add("Cat");
        animals.Add("Dog");
        animals.Add("Squirrel");
        animals.Add("Wolf");

        Console.WriteLine();
        foreach (string animal in animals)
        {
            Console.WriteLine(animal);
        }

        Console.WriteLine("\nIList<string> roAnimals = animals.AsReadOnly()");
        IList<string> roAnimals = animals.AsReadOnly();

        Console.WriteLine("\nElements in the read-only IList:");
        foreach (string animal in roAnimals)
        {
            Console.WriteLine(animal);
        }

        Console.WriteLine("\nanimals[2] = \"Lion\"");
        animals[2] = "Lion";

        Console.WriteLine("\nElements in the read-only IList:");
        foreach (string animal in roAnimals)
        {
            Console.WriteLine(animal);
        }
    }
}

/*
    This code example produces the following output:

    Capacity: 4

    Cat
    Dog
    Squirrel
    Wolf

    IList<string> roAnimals = animals.AsReadOnly()

    Elements in the read-only IList:
    Cat
    Dog
    Squirrel
    Wolf

    animals[2] = "Lion"

    Elements in the read-only IList:
    Cat
    Dog
    Lion
    Wolf
*/
Imports System.Collections.Generic

Partial Public Class Program
    Public Shared Sub Main()

        Dim animals As New List(Of String)(4)

        Console.WriteLine(vbLf & "Capacity: {0}", animals.Capacity)

        animals.Add("Cat")
        animals.Add("Dog")
        animals.Add("Squirrel")
        animals.Add("Wolf")

        Console.WriteLine()
        For Each animal As String In animals
            Console.WriteLine(animal)
        Next

        Console.WriteLine(vbLf & _
            "Dim roAnimals As IList(Of String) = animals.AsReadOnly")
        Dim roAnimals As IList(Of String) = animals.AsReadOnly

        Console.WriteLine(vbLf & "Elements in the read-only IList:")
        For Each animal As String In roAnimals
            Console.WriteLine(animal)
        Next

        Console.WriteLine(vbLf & "animals(2) = ""Lion""")
        animals(2) = "Lion"

        Console.WriteLine(vbLf & "Elements in the read-only IList:")
        For Each animal As String In roAnimals
            Console.WriteLine(animal)
        Next

    End Sub
End Class

' This code example produces the following output:
'
' Capacity: 4
'
' Cat
' Dog
' Squirrel
' Wolf
'
' Dim roAnimals As IList(Of String) = animals.AsReadOnly
'
' Elements in the read-only IList:
' Cat
' Dog
' Squirrel
' Wolf
'
' animals(2) = "Lion"
'
' Elements in the read-only IList:
' Cat
' Dog
' Lion
' Wolf

Remarks

The capacity of a List<T> is the number of elements that the List<T> can hold. As elements are added to a List<T>, the capacity is automatically increased as required by reallocating the internal array.

If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the List<T>.

The capacity can be decreased by calling the TrimExcess method or by setting the Capacity property explicitly. Decreasing the capacity reallocates memory and copies all the elements in the List<T>.

This constructor is an O(1) operation.

See also

Applies to