Arrays are nice, but they have a problem: once created, their size is fixed. What if you don't know how many items you'll have? That's where collections come in โ they grow and shrink as needed.
List<T>
List<T> is a dynamic array. The T is the type of elements it holds. You can add, remove, and access items just like an array, but it resizes automatically.
List names = new List();
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");
Console.WriteLine(names[0]);
Console.WriteLine("Count: " + names.Count);
Try it Yourself โ
Working with Lists
Lists give you useful methods: Add, Remove, Contains, Insert, Sort, and more.
List fruits = new List();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Cherry");
fruits.Remove("Banana");
fruits.Insert(1, "Blueberry");
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Dictionary<TKey, TValue>
A dictionary stores key-value pairs. You look up a value by its key, like a real dictionary. Keys must be unique.
Dictionary ages = new Dictionary();
ages["Alice"] = 30;
ages["Bob"] = 25;
ages["Charlie"] = 35;
Console.WriteLine(ages["Alice"]);
foreach (KeyValuePair entry in ages)
{
Console.WriteLine(entry.Key + ": " + entry.Value);
}
Use ContainsKey to check if a key exists before accessing it, or use TryGetValue to avoid exceptions.
Choosing a Collection
- List<T> โ ordered items, access by index, duplicates allowed
- Dictionary<TKey, TValue> โ fast lookup by key, unique keys
- HashSet<T> โ unique elements, no ordering, fast membership checks
- Queue<T> โ first-in, first-out (like a line)
- Stack<T> โ last-in, first-out (like a pile)