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:
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 () .
ridoy
source share