List is a generic class and is defined in the System.Collections.Generic namespace. You must import this namespace in your project to access the List<T> class.
1 2 3 |
using System.Collections.Generic; |
List<T> class constructor is used to create a List object of type T. It can either be empty or take an Integer value as an argument that defines the initial size of the list, also known as capacity. If there is no integer passed in the constructor, the size of the list is dynamic and grows every time an item is added to the array. You can also pass an initial collection of elements when initialize an object.
The following code snippet creates a List of Int16 and a list of string types. The last part of the code creates a List<T> object with an existing collection.
1 2 3 4 5 6 7 8 |
// List with default capacity List<Int16> list = new List<Int16>(); // List with capacity = 5 List<string> authors = new List<string>(5); string[] animals = { "Cow", "Camel", "Elephant" }; List<string> animalsList = new List<string>(animals); |
The List<string> has an initial capacity set to 5 only. However, when more than 5 elements are added to the list, it automatically expands.