19

I see this:

This packages provides collections that are thread safe and guaranteed to never change their contents, also known as immutable collections.

But i dont understand what is exactly and when we should use ImmutableArray?

Edit: nowadays, Microsoft's github package has become part of the .NET ecosystem. Reference is now here.

Abel
  • 56,041
  • 24
  • 146
  • 247
  • 1
    Immutable means unchangeable FYI – FabianCook Jun 26 '13 at 11:24
  • 4
    Did you follow the links from Nuget [to here](http://blogs.msdn.com/b/bclteam/archive/2012/12/18/preview-of-immutable-collections-released-on-nuget.aspx)? – Martin Smith Jun 26 '13 at 11:24
  • So that covers some use cases in the "Why should I use immutability?" section. What additional "when" do you need? – Martin Smith Jun 26 '13 at 11:25
  • This means mutable: `myList[0].PropertyAbc = newValue;`. Read Lippert's Blog: [Immutability in C# Part One: Kinds of Immutability](http://blogs.msdn.com/b/ericlippert/archive/2007/11/13/immutability-in-c-part-one-kinds-of-immutability.aspx) – Tim Schmelter Jun 26 '13 at 11:26
  • http://msdn.microsoft.com/en-us/library/ms132474.aspx – Marcus Jun 26 '13 at 11:33
  • A `string` is an immutable `char` array in .NET – John Alexiou Jun 26 '13 at 13:30
  • Related: [Difference between ImmutableArray and ImmutableList](https://stackoverflow.com/questions/22349861/difference-between-immutablearrayt-and-immutablelistt/22349914) – Theodor Zoulias Mar 20 '22 at 08:45
  • 1
    @TimSchmelter, links dead, but available at https://ericlippert.com/2007/11/13/immutability-in-c-part-one-kinds-of-immutability/ – KyleMit Sep 13 '22 at 19:51

2 Answers2

21

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.

Abel
  • 56,041
  • 24
  • 146
  • 247
FabianCook
  • 20,269
  • 16
  • 67
  • 115
  • 2
    `readonly` is a C# modifier for field declarations so it is confusing to use the term in relation to immutable objects in .NET. They are separate concepts. – Tom Blodget Jun 26 '13 at 18:31
  • Yeah, should have really used different wording. – FabianCook Jun 26 '13 at 21:15
  • 1
    I know it's an old answer, but still people find it so I've updated your answer to reflect your comments (and fixed the sample). Hope it's OK. – Abel Dec 13 '19 at 10:10
19

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().

Abel
  • 56,041
  • 24
  • 146
  • 247
ridoy
  • 6,274
  • 2
  • 29
  • 60
  • 1
    Can you substantiate why it has a memory disadvantage? I presume this is in terms of memory space required? – Patrick Feb 28 '19 at 12:23
  • @patrick, details [are explained here](https://blogs.msdn.microsoft.com/bclteam/2012/12/18/preview-of-immutable-collections-released-on-nuget/). Basically, each time you update an immutable array, it will copy all its contents to the new array. However, since immutable arrays are implemented as binary trees, only the effected nodes need to be updated, making this `O(log n)` performance in speed and the old + new array only slightly uses more memory than full copies of both would. So there is a memory trade off, but not as significant as one might think on the surface. – Abel Dec 13 '19 at 11:05
  • 3
    @Abel and ridoy: As stated in this [Microsoft article](https://devblogs.microsoft.com/dotnet/please-welcome-immutablearrayt/) and confirmed by [their source code](https://github.com/tunnelvisionlabs/dotnet-collections/blob/master/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray%601.cs), `ImmutableArray` is implemented as an array, not a tree. The author of that article specifically advocates choosing `ImmutableArray` over `ImmutableList` when you desire the performance characteristics of arrays rather than trees. – MarredCheese Jan 07 '21 at 04:36
  • @Patrick Regarding your question, see my previous comment. Here's an excerpt from the article I linked to: "`ImmutableArray` is a very thin wrapper around a regular array and thus shares all the benefits with them. ...Passing around an immutable array is as cheap as passing around the underlying array." – MarredCheese Jan 07 '21 at 05:23
  • @marred You're right, the link and story I refer to applies to `ImmutableList` and the like, not to arrays, immutable or not. – Abel Jan 11 '21 at 10:02