Lists
8 min · C#
C#'s resizable lists — add, remove, and reach items by index.
Enemy 1 of 5
List<T> vs. a plain array
A plain C# array has a fixed size chosen at creation. List<T> (from the System.Collections.Generic namespace) is the resizable alternative most C# code reaches for by default: it can grow or shrink as your program runs, without you managing the underlying memory yourself.
The <T> is a type parameter — List<string> is a list that only ever holds strings, List<int> only ever holds ints. Locking down the element type like this means the compiler will catch an attempt to add the wrong kind of value long before your program runs, the same benefit typed variables give you elsewhere in C#.
new List<string> { "apple", "banana", "cherry" } creates a list already populated with three items. .Add(value) appends one more item onto the end afterward, and [index] reads back an item by its position, counting from 0 just like arrays and strings.
Loading editor...