We all are aware of .Net Collections and its general usgae in .Net applications. But, often we fail to select the appropriate Collection and we realize that after encountering a problem in the middle of development activity.
So, what's the proper way to use collections in .Net? Well, Microsoft has already provided good information on that which I will emphasize here.
Firstly, what are Collections in .Net and its types?
Collections provides a more flexible way to create and manage groups of related objects. There are two ways of grouping objects: Arrays and Collections. Generally, Arrays are used for a fixed number of objects and if it's dynamic then we should always go for Collections.
All the collections are derived from either the System.Collections, System.Collections.Generic, System.Collections.Concurrent, or System.Collections.Immutable namespace.
So, generally collections are categorized into two types - Generic and Non-Generic Collections. Generic collections were added in the .NET Framework 2.0 and provide collections that are type-safe at compile time. Because of this, generic collections typically offer better performance.
Features of Collections
Though all the collections have the ability to add, remove or find items in a collection they also have some additional features as mentioned below,
- Ability to enumerate collections.
- Ability to copy collection contents to an array.
- Capacity and Count properties.
- Consistent lower bound.
- Synchronization for access from multiple threads.
Now let's explore below in which situation we can use different collections - officially from here.
I want to… |
Generic collection options |
Non-generic collection options |
Thread-safe or immutable collection options |
Store items as key/value pairs for quick look-up by key |
Dictionary<TKey,TValue> |
Hashtable
(A collection of key/value pairs that are organized based on the hash code of the key.) |
ConcurrentDictionary<TKey,TValue>
ReadOnlyDictionary<TKey,TValue>
ImmutableDictionary<TKey,TValue> |
Access items by index |
List<T> |
Array
ArrayList |
ImmutableList<T>
ImmutableArray |
Use items first-in-first-out (FIFO) |
Queue<T> |
Queue |
ConcurrentQueue<T>
ImmutableQueue<T> |
Use data Last-In-First-Out (LIFO) |
Stack<T> |
Stack |
ConcurrentStack<T>
ImmutableStack<T> |
Access items sequentially |
LinkedList<T> |
No recommendation |
No recommendation |
Receive notifications when items are removed or added to the collection. (implements INotifyPropertyChangedand INotifyCollectionChanged) |
ObservableCollection<T> |
No recommendation |
No recommendation |
A sorted collection |
SortedList<TKey,TValue> |
SortedList |
ImmutableSortedDictionary<TKey,TValue>
ImmutableSortedSet<T> |
A set for mathematical functions |
HashSet<T>
SortedSet<T> |
No recommendation |
ImmutableHashSet<T>
ImmutableSortedSet<T> |
That's it for part 1 of .Net Collections. From Part 2 onwards we will explore all these collections and their usage with the code in C#.