What is ImmutableArray in C #

I see this :

These packages provide collections that are thread safe and guaranteed to never modify their contents, also known as immutable collections.

But I do not understand what exactly and when should we use ImmutableArray?

+8
c #
source share
3 answers

An optional array will be a readonly object, unlike an ExpandoObject

This means that after defining it is not possible to change the values ​​(unless you define it again)

For example:

 ImmutableByteArray byteArray = new ImmutableByteArray(new byte[] { 0, 1, 2, 3 }); 

They will always have the values ​​specified by the new byte[] { 0, 1, 2, 3 } mutable array, if it is not defined again.

+6
source share

An immutable object can be defined as an object whose state cannot be changed after its creation. The most widely used immutable object is by far the String object. Being objects are useful when a thread safety issue is a problem and / or when an instance of an object must be accessible outside of your code in readonly mode.
<strong> Benefits:

  • Thread safety
  • It is safe to pass a reference to an immutable object outside the class without the risk of data changes.

Disadvantages:

  • Memory usage

How to use:

 using ImmutableByteArray = System.ImmutableArray<byte>; using ImmutableCharArray = System.ImmutableArray<char>; 

An immutable array can also be created from a mutable array, for example ..

 ImmutableByteArray array1 = new ImmutableByteArray(new byte[] { 0, 1, 2, 3 }); ImmutableCharArray string = new ImmutableCharArray("test".ToCharArray()); 

We can create an immutable array from another immutable array.

 ImmutableByteArray array2 = new ImmutableByteArray(new byte[] { 0, 1, 2, 3 }); ImmutableByteArray array3 = array1 + array2; 

In this case, array3 does not consume additional memory.
ImmutableArray supports enumeration . Use it as ..

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

And can implement the ICloneable interface.

 array5 = array1.Clone(); 

ImmutableArray also overrides and implements the Equals () and '==' and '! = '.

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

For now, you can use the above line of code in the case of array1! = Array2 just like ! Equals () .

+7
source share

I want to explain to you about immutable collections, but it is better if you read more detailed information here: http://blogs.msdn.com/b/bclteam/archive/2012/12/18/preview-of-immutable-collections-released -on-nuget.aspx

+1
source share

All Articles