.NET Collections
Updated on October 17 2024
Introduction
Sometimes, the proper choice of a collection can greatly impact the performance of your application. For example, there are collection types that are more appropriate for insertions, others that allow faster lookups, and so on. Plus, you must decide if you want indexed collections or not, and if you want to have generic collections, in order to have compile-time type checking. The .NET BCL comes with several general-purpose collection classes. Here is a list of all the collection classes in .NET 9 and their intended use.
Namespaces
Namespace | Purpose |
System.Collections | Basic types, non-generic collections and interfaces |
System.Collections.Generic | Generic interfaces and collections |
System.Collections.ObjectModel | Observable and read-only collections |
System.Collections.Specialized | Special collections |
System.Collections.Concurrent | Concurrent (thread-safe) collections |
System.Collections.Immutable | Immutable collections |
System.Collection.Frozen | Frozen collections |
Collections
Interfaces
Of course, you should not expose a collection class directly because it couples you to a an implementation, instead you should use collection interfaces, all these classes implement (at least) one of them). These interfaces are:
Purpose | Types |
---|---|
Enumerate only |
System.Collections.IEnumerable, System.Collections.IEnumerable<T> System.Linq.IOrderedEnumerable<T> System.Linq.ILookup<K, E> (multiple values per key) |
Enumerate, count | |
Indexed access, add/remove (where not read-only or immutable) |
System.Collections.Generic.IList<T> System.Collections.Immutable.IImmutableList<T> |
Keyed |
System.Collections.IDictionary System.Collections.Specialized.IOrderedDictionary System.Collections.Generic.IDictionary<K, V> |
FIFOs (Queues) | System.Collections.Immutable.IImmutableQueue<T> |
LIFOs (Stacks) | System.Collections.Immutable.IImmutableStack<T> |
Sets |
System.Collections.Generic.ISet<T> |
Frozen vs Immutable vs Read Only Collections
The difference between frozen and immutable is: frozen collections start as mutable, allowing you to add content to them, and once you are done adding or modifying elements, you can freeze the collection, thus making it immutable. Frozen collections are faster than the others. Read only are just that, read only. Read more here and here.
Best Practices
Some recommendations for using collections:
- Always prefer generic collections (should be obvious by now!);
- Always expose collections in properties, not arrays, and always collections with the less access possible (enumerate only, or read-only access to elements);
- All collections except synchronized and concurrent are not thread-safe;
- When using a collection where you need random inserts/removes at specific positions, prefer a linked list over an array-based implementation, as the latter requires constant allocations and copies;
- Choose a collection that better suits your intent (no repetition of items, indexed, always sorted, ...);
- Collections that rely on object identity (hashed/keyed collections) may need proper implementation of Equals or GetHashCode methods; the implementation of the two should be consistent;
- For customized object equality comparison, a custom implementation of System.Collections.Generic.IEqualityComparer<T> or System.Collections.IEqualityComparer may be passed on the constructor;
- For sorted collections, a custom implementation of System.Collections.Generic.IComparer<T> or System.Collections.IComparer may be passed on the constructor (System.Collections.Comparer, System.Collections.CaseInsensitiveComparer are default implementations);
- Indexed and sorted collections rely on a proper, consistent and stable implementation of GetHashCode. It cannot ever change for the same object, or things may go wrong with the collection - object may not be found, for example;
- If number of elements is known beforehand, use the constructor that specifies the initial capacity;
- Immutable collections always return new objects when adding or removing from an existing one;
- Cannot add or remove from a frozen collection;
- Avoid using value types for elements, except for keys, because they need to be copied bit by bit, unlike with reference types, where only their pointer is copied.
Performance
Some tips regarding performance:
- Prefer using foreach to iterate through a array, or, in general, any collection, unless it's an indexed one (List<T>, Dictionary<K, V>, etc)
- In a for loop, do not cache the Length or Count values, no need, and can in fact be worse
- Fastest way to loop over a List<T> is by using CollectionsMarshal.AsSpan
And that's it.