A generic collection in C# is a collection class that can store objects of a specific type, specified when the collection is created. Unlike non-generic collections, generic collections enforce type safety at compile time, preventing invalid types from being added and improve performance by eliminating the need for boxing/unboxing for value types.
Common Generic Collections in C#
1. List<T>
A dynamic array that automatically resizes as items are added. Provides indexed access, searching and sorting.
List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
Console.WriteLine(names[0]); // Alice
- Maintains order of elements
- Dynamic resizing
- Supports LINQ operations
2. Dictionary<TKey, TValue>
Stores key-value pairs for fast lookups by key.
Dictionary<int, string> users = new Dictionary<int, string>();
users.Add(1, "Alice");
users.Add(2, "Bob");
Console.WriteLine(users[2]); // Bob
- Fast retrieval using keys
- Prevents duplicate keys
- Ideal for mapping relationships
3. Queue<T>
Represents a first-in, first-out (FIFO) collection.
Queue<int> numbers = new Queue<int>();
numbers.Enqueue(1);
numbers.Enqueue(2);
Console.WriteLine(numbers.Dequeue()); // 1
- Maintains insertion order
- Suitable for task scheduling or processing
4. Stack<T>
Represents a last-in, first-out (LIFO) collection.
Stack<string> stack = new Stack<string>();
stack.Push("First");
stack.Push("Second");
Console.WriteLine(stack.Pop()); // Second
- Last element added is the first to be removed
- Useful for undo functionality, parsing and recursion simulations
5. HashSet<T>
Stores unique elements without duplicates.
HashSet<int> numbers = new HashSet<int>();
numbers.Add(1);
numbers.Add(1); // Returns false if element already exists
Console.WriteLine(numbers.Count); // 1
- Ensures uniqueness of elements
- Supports set operations like Union, Intersection and Difference
6. SortedList<TKey, TValue>
Stores key-value pairs sorted by key automatically.
SortedList<int, string> sortedUsers = new SortedList<int, string>();
sortedUsers.Add(2, "Bob");
sortedUsers.Add(1, "Alice");
Console.WriteLine(sortedUsers.Keys[0]); // 1
- Maintains sorted order of keys
- Quick retrieval by key
- Useful for ordered mappings
Choosing the Right Collection
- Use List<T> for dynamic arrays and ordered lists.
- Use Dictionary<TKey, TValue> for key-value mappings with fast lookups.
- Use Queue<T> and Stack<T> when order of insertion or removal matters.
- Use HashSet<T> to ensure element uniqueness.
- Use SortedList<TKey, TValue> when you need automatically sorted key-value pairs.