devxlogo

Immutable Collections

Immutable Collections

With asynchronous programming and TPL gaining popularity amongst .NET developers, the general availability of a stable release for the Immutable Collections feature has found a strong audience with developers especially in the world of cross platform app development, where lot of the data transfer code is wrapped in portable class libraries and is shared across different multi-threaded clients in the form of Windows 8, Store, or WPF applications. What is interesting is that the immutable collections are not part of the core framework. Instead, they are required to be separately installed using the Microsoft.Bcl.Immutable?package. Note that there has been recent additions to the package that are still in preview (such as the addition of ImmutableArray), so to explore the newly added members, you must select the pre-release option instead of the stable version in the package manager or console.

Install-Package Microsoft.Bcl.Immutable -Pre

Earlier thread-safe patterns (early TPL days) would promote usage of concurrent collections which are a definite alternative to immutable collections, however an expensive one. Concurrent collections, internally use expensive locking mechanisms for thread safety that immutable collections are able to avoid. It is interesting to note that internal nodes in immutable collections are not immutable to reduce garbage during the construction of the collection.

Another important thing to note is that immutable collections only offer reference equality to avoid expensive computations of value equality on collections.

Once you have installed the nuget package, you can start using immutable collections in your application / library. You will also notice the ToImmutableList()?extension on collections. A good design practice for using immutable collections is to make the immutable collection properties read-only, and set them using the constructor.

public Cart(IEnumerable items)    {        Items = items.ToImmutableList();    }    public ImmutableList Items { get; private set; }

Now in your comparison methods, you can compare the instances and avoid creating a new instance of Item in case of a match in a thread-safe fashion.

return Object.ReferenceEquals(Items, value) ? this : new Item(value); 

Recommended practice is also to use the Create method when creating a new instance of an immutable collection or use the builder where the nodes are not frozen until the ToImmutable call is made.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist