Mutations be gone: Microsoft .NET releases immutable collections

Sep 26, 2013

Nine months after preview, the Microsoft .NET team has released a ready-for-primetime package of immutable collections on the NuGet Gallery. I know what you’re thinking, “The .NET Framework already includes many highly tuned generic collections, so what’s the fuss?” Those familiar with collections know that read-only collection types are in essence facades over collections that can change at any time.

The folks at the Base Class Library Blog explain it best: If someone hands you a ReadOnlyCollection<T>, an IReadOnlyList<T>, or an IEnumerable<T>, the only guarantee is that you can’t change the data –the person that handed you the collection, on the other hand, is free to make changes. These types of collections don’t offer events to notify you when their contents change, and if they do change, what if that occurs on a different thread, while you’re enumerating its contents? This would lead to data corruption and/or random exceptions in your application.

In contrast, if someone provides you with data via an immutable type, the guarantee is that the data will never change. You can hold a reference to it as long as you want and stay completely confident that you’ll get the expected behavior.

What’s more, by working with immutable collections, you can reduce memory allocation and increase performance.

The Microsoft Immutable Collections support .NET Framework 4.5, .NET for Windows Store apps, Windows Phone 8, and Portable Class Libraries platforms.

Find out more about this release, plus examples and videos, in today’s post on the .NET Framework Blog.

You might also be interested in:

Deborah Pisano
Microsoft News Center Staff