What is ImmutableArray in c#

Immutable objects may be defined as an object whose state cannot be modified after it is created. The most widely used immutable object is certainly the String object. Immutable objects are useful when thread safety is a concern and/or when an instance of an object must be accessed outside of your code in a readonly mode.

Advantages:

  • Thread safety
  • It is secure to pass a reference of an immutable object outside of a class without the risk that the data could be changed

Disadvantages:

  • Memory usage
  • Speed for update and append is O(log n) (it is implemented as binary trees)

How to use:

Generally speaking, you would use the factory methods of the ImmutableArray static class, as described here.

// open the namespace
using System.Collections.Immutable;

An immutable array can be created from a mutable array like:

var array1 = ImmutableArray.Create<byte>(new byte[] { 0, 1, 2, 3 });
var astring = ImmutableArray.Create<char>("test".ToCharArray());

Or we can create the immutable array from another immutable array..

var array2 = ImmutableArray.Create<byte>(new byte[] { 0, 1, 2, 3 });
var array3 = array1 + array2;

In this case, array3 does not consume further memory.
ImmutableArray supports enumeration, i.e. IEnumerable<T>. So it can be uses like:

foreach (byte b in array1)
    Console.Write(b + " ");

And it implements the ICloneable interface:

array5 = array1.Clone();

ImmutableArray<T> also overrides and implements Equals() and '==' and '!=' operators.

// similar to array1 == array2
Console.WriteLine("array1 equals array2: {0}", (array1.Equals(array2)); 

So far you can use above line of code in case of array1 != array2 as same as ! Equals().


An immutable array would be similar, but not quite the same as a readonly object. The latter can be used to prevent you from changing it, but it can still be changed by others. An immutable array is guaranteed to be never changed, unlike something like an ExpandoObject or most other objects lists and stays in C#.

This also means that the values can't be changed after definition,or that the array can be appended to. When using methods to change or update, you'll receive a new immutable array.

For example:

ImmutableArray<byte> byteArray = ImmutableArray.Create(new byte[] { 0, 1, 2, 3 });

Will always have the values given by the mutable array new byte[] { 0, 1, 2, 3 }, unless it is defined again.