What are Immutable Collections?
Immutable Collections are collections which guarantees that they never change their content and completely thread safe. Immutable suggests that data will not change and will not ever change and moreover you can hold a reference to it as long as you want. Why should we use Immutable Collections when there are Readonly Collections like ReadOnlyCollection<T>, an IReadOnlyList<T>, or an IEnumerable<T>. You can not change the data but there is not guarantee that the person handed you the collection wonâ€™t change it. So there is a chance of change in the content when you enumerate on ReadOnlyCollection.
The NuGet package preview includes these types:
- ImmutableDictionary<K, V>
- ImmutableSortedDictionary<K, V>
Example: Using ImmutableList<T>
Empty is a static property which allows you to return an empty list singleton where you can reuse it in your application. Adding an element to this list as follows
Add method returns a new list which assigned to a new variable. Note the list vechicleList is still empty. This is like System.String. Mutating the immutable collection as follows
More on this topic can be read here
|Share this post :