Roadmap › C# Language — Basics to Advanced › Module: Arrays and Collections
Lessons in this course (38)
10. Collections overview: generic vs non-generic
Basic★ Must knowLesson 10 of 38
| Type | When to use | Lookup |
|---|---|---|
T[] | Fixed size | O(1) by index |
List<T> | Growable list | O(1) index, O(n) search |
Dictionary<TKey,TValue> | Key → value | O(1) average |
HashSet<T> | Unique items, fast Contains | O(1) average |
Queue<T> / Stack<T> | FIFO / LIFO | O(1) enqueue/push |
LinkedList<T> | Many inserts/removes in the middle | O(1) insert with a node |
SortedDictionary / SortedList | Ordered keys | O(log n) |
ConcurrentDictionary, ConcurrentQueue | Multi-threaded access | thread-safe |
ImmutableList, FrozenDictionary (.NET 8) | Read-only shared data | — |
csharp
var prices = new Dictionary<string, decimal> { ["pen"] = 10m, ["book"] = 250m };
if (prices.TryGetValue("pen", out var p)) Console.WriteLine(p);
int[] nums = [5, 3, 8]; // collection expression (C# 12)
List<int> list = [.. nums, 10]; // spreadIEnumerable<T>= can be iterated;ICollection<T>adds Count/Add/Remove;IList<T>adds index access.- Prefer returning
IReadOnlyList<T>/IEnumerable<T>from public APIs.
Generic vs non-generic collections:
Non-generic (System.Collections, .NET 1.x) | Generic replacement (System.Collections.Generic, .NET 2.0+) |
|---|---|
ArrayList | List<T> |
Hashtable | Dictionary<TKey, TValue> |
SortedList | SortedList<TKey, TValue> |
Stack, Queue | Stack<T>, Queue<T> |
Generic collections are type-safe (compile-time errors instead of runtime InvalidCastException) and faster for value types (no boxing). Use the non-generic ones only when maintaining old code.