Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

Immutable Collections

.NET Framework 4.5

It can be challenging to keep mutable state under control when multiple threads are involved. A common approach is to make use of immutable state that can be passed freely between different threads. Immutable collections are different from read-only collections in the sense that unlike read-only collections, they cannot be changed by the provider or consumer of the collection. For example, if you are enumerating a read-only collection, there is a possibility that the collection can be changed on another thread, causing data corruption. This scenario can’t occur if you are using an immutable collection.

With immutable collections, you can:

  • Share a collection in a way that its consumer can be assured that the collection will never change.

  • Provide implicit thread safety in multi-threaded applications (no locks required to access collections).

  • Follow functional programming practices.

  • Modify a collection during enumeration, while ensuring that the original collection does not change.

The immutable collection classes are supported starting with the .NET Framework 4.5. Use them to build apps that target the desktop, the Windows Store, Portable Class Library, and Windows Phone 8.

The immutable classes are not part of the core class library distributed with the .NET Framework; they are available via NuGet. To install these classes:

  1. Open your project in Visual Studio and choose Manage NuGet Packages from the Project menu.

  2. In the left pane, choose Online.

  3. Optionally, in the drop-down list box in the middle pane, choose Include Prerelease instead of Stable Only. This option will give you access to new prerelease versions of the immutable classes, as they become available. (To use ImmutableArray<T> you must choose Include Prerelease.)

  4. In the right pane, use the Search box to locate the Microsoft.Immutable.Collections (Microsoft.Bcl.Immutable) package.

  5. In the middle pane, select Microsoft Immutable Collections, and then choose Install.

The System.Collections.Immutable namespace provides generic immutable collection types that you can use for these scenarios, including:

The namespace contains many supporting classes as well. For example, each immutable collection type typically has an associated builder type that enables you to easily and efficiently create and manipulate a collection before making it immutable. See the System.Collections.Immutable namespace for a full list of types and links to reference content.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.