LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 3220 min read

Collections

Learn List, Dictionary, and other core collection types in the System.Collections.Generic namespace.

Why Not Just Use Arrays?

Arrays have a fixed size. The `System.Collections.Generic` namespace provides growable, feature-rich collection types that are far more commonly used in real applications.

List<T>

`List<T>` is a growable, ordered collection — the most commonly used collection type in C#.

List<string> names = new List<string> { "Alice", "Bob" };
names.Add("Charlie");
names.Remove("Bob");
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.WriteLine($"Count: {names.Count}");
Output

Click Run to see what this code prints.

Dictionary<TKey, TValue>

A `Dictionary` stores key-value pairs, giving fast lookups by key.

Dictionary<string, int> ages = new Dictionary<string, int>
{
{ "Alice", 30 },
{ "Bob", 25 }
};
ages["Charlie"] = 35; // add or update
Console.WriteLine(ages["Alice"]);
if (ages.TryGetValue("Dave", out int daveAge))
{
Console.WriteLine(daveAge);
}
else
{
Console.WriteLine("Dave not found.");
}
Output

Click Run to see what this code prints.

HashSet<T>

A `HashSet<T>` stores only unique values with fast membership checks — perfect for de-duplicating data or set operations.

HashSet<int> uniqueNumbers = new HashSet<int> { 1, 2, 2, 3, 3, 3 };
Console.WriteLine(uniqueNumbers.Count); // 3 — duplicates removed

FAQs

For most application code, yes — List<T> is more flexible. Arrays still make sense for fixed-size, performance-critical, or interop scenarios.

Summary

  • List<T> is a growable, ordered collection.
  • Dictionary<TKey, TValue> gives fast key-based lookups.
  • HashSet<T> stores only unique values.
Next Lesson →

Generics