Loading lessons...
Collections & Generics
Collections & Generics
Collections are containers for groups of objects. The most useful ones are generic - they work with any type.
List<T>
A List<T> is like a resizable array:
using System.Collections.Generic;
List<string> cars = new List<string>();
cars.Add("Volvo");
cars.Add("BMW");
Console.WriteLine(cars[0]); // Volvo
cars.Remove("Volvo");
Console.WriteLine(cars.Count); // 1
The <T> means generic
The <T> in List<T> is a type parameter. List<int>, List<string>, and List<Car> are all lists, but each holds only its own type. This gives you type safety - the compiler stops you from mixing types.
Dictionary<TKey, TValue>
A dictionary stores key/value pairs for fast lookups:
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Ada"] = 36;
ages["Grace"] = 85;
Console.WriteLine(ages["Ada"]); // 36
Other common collections
HashSet<T>- unique values, no duplicates.Queue<T>- first-in, first-out.Stack<T>- last-in, first-out.LinkedList<T>- fast insertions in the middle.
Arrays vs List
- Array: fixed size, great when you know the count.
- List<T>: grows and shrinks automatically, more flexible.
TL;DR
List<T>is a resizable, type-safe array.<T>makes a collection generic (works with any type).Dictionary<TKey, TValue>stores key/value pairs.- Use
using System.Collections.Generic;to access them.