List<T> is an zero based, expandable size collection of elements, meaning first index of a List<T> is 0, once we initialize a List<R> we can change it’s length add or remove elements. List<T> is an reference type. System.Collections.Generic.List class holds methods that we can use with List<T>. Note that Generic List is similar to an Array.

Declaration

List<T> can can contain reference or value types. We declare a List<T>  by typing List followed by<> (angle brackets) and inside <> should be desired type of our List<T> and after that should be variable name:

 

Initialization

As List<T> is an reference type so we initialize it by assigning List variable to List<T> instance. Type of List should be specified while instantiating List<T>.

Populating a List<T> with values

Add element to end of a List

 

Using collection initializer

 

Add element to specific index in a List<T>

This action will insert element on index value 1.

Remove an element from the List<T>

Remove element by value

This action will remove first occurrence of “Tokyo” string inside of a List.

Remove element by index value

This action will remove element at index value 3.

How to use generic List<T>

Retrieve value by index

We retrieve an element from List<T> by specifying index of that value. If for example we wanted to retrieve first element from our previous List we can access that value like this:

Of course if we have List of objects we can specify index of an element and select property to display

Iterate through List<T>

We can iterate an List<T> using for and foraech statements

 

 

Find value at specified index

 

Number of elements inside of a List<T>

Capacity of a list

Note that Capacity property value can be different than that of Count property. Count property value tells us how many elements are inside of an List, but Capacity value tells us how many elements List<T> can hold before it expands. Default List<T> capacity is 4, and every time we add more elements than List<T> can hold capacity value doubles.

Good practices for using List<T>:

Use plural variable name. Variable name cityNames is better naming convention than cityName.

Use List<T> if you do not know List size during design time because List<T>size can be changed during runtime.