Search code examples
c#immutablearray

What is ImmutableArray in c#


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.


Solution

  • 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.