Collections in .NET
The .NET framework provides a rich set of collection types that simplify data storage, retrieval, and manipulation. Whether you need a dynamic list, a key‑value map, or a thread‑safe queue, .NET has a collection tailored to your scenario.
When to Use Which Collection?
| Scenario | Recommended Collection | Key Features |
|---|---|---|
| Ordered, index‑based access | List<T> |
Dynamic resizing, fast random access |
| Key‑value lookup | Dictionary<K,V> |
O(1) lookups, unique keys |
| Fixed size, contiguous memory | Array |
Fast iteration, low overhead |
| First‑in‑first‑out processing | Queue<T> |
Enqueue/Dequeue O(1) |
| Last‑in‑first‑out processing | Stack<T> |
Push/Pop O(1) |
| Data binding & UI updates | ObservableCollection<T> |
Change notifications |
Common Operations
// Create a list
var numbers = new List<int> { 1, 2, 3 };
// Add an element
numbers.Add(4);
// Remove by value
numbers.Remove(2);
// Iterate
foreach (var n in numbers)
{
Console.WriteLine(n);
}
// Dictionary example
var ages = new Dictionary<string, int>();
ages["Alice"] = 30;
ages["Bob"] = 25;
Console.WriteLine(ages["Alice"]);
Performance Tips
- Prefer
List<T>overArrayListfor type safety and better performance. - When the collection size is known and unchanged, use an
Arrayto reduce allocation overhead. - For large datasets that require frequent lookups,
Dictionary<K,V>provides constant‑time access. - Use
ReadOnlyCollection<T>orIReadOnlyList<T>to expose data without allowing modifications.