Techbubbles

Immutable Collections in .NET Framework

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:

  • ImmutableStack<T>
  • ImmutableQueue<T>
  • ImmutableList<T>
  • ImmutableHashSet<T>
  • ImmutableSortedSet<T>
  • ImmutableDictionary<K, V>
  • ImmutableSortedDictionary<K, V>

Example: Using ImmutableList<T>

   1: var vehicleList = ImmutableList<string>.Empty;

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

   1: var vehicleListWithCar = vechicleList.Add("Car");

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

   1: private ImmutableHashSet<Customer> customers;

   2:  

   3: public ImmutableHashSet<Customer> GetCustomersInDebt()

   4: {

   5:     return this.customers.Except(c => c.Balance >= 0.0);

   6: }    

More on this topic can be read here

Share this post :


Related Posts:

  • Larry

    Hi,
    Good one!! I learnt about this immutable collections today and clearly understood why are they preferred over ReadOnlyCollection. Thanks for redirecting for a more detailed webpage as well which helped me further.

%d bloggers like this: