If an object can change its state, it is difficult to use in multiple tasks running simultaneously. These collections must be synchronized. If the object cannot change the state of the device, it is easy to use in multiple threads.
Microsoft provides a new collection library: Microsoft Immutable Collection. As the name implies, it contains unchanged collection classes—— collection classes that cannot be changed after creation. This class is defined in.
//Create the array using the static Create method. The Create method is overloaded and can pass any number of elements ImmutableArray<string> a1 = <string>(); //Add method will not change the invariant set itself, but will return a new invariant set ImmutableArray<string> a2 = ("Williams"); //You can call multiple Add methods at once ImmutableArray<string> a3 = ("Ferrari").Add("Mercedes").Add("Red Bull Racing"); foreach (var item in a3) { (item); }
At each stage where the invariant array is used, the complete collection is not copied. Instead, the invariant type uses a shared state, and the collection is copied only if needed.
However, it is more efficient to populate the collection first and then turn it into an invariant array (using the ToImmutableList method). When some processing is required, it can be changed to a mutable collection (using the ToBuilder method). Use the provided builder ImmutableList<Account>.Builder for the invariant collection.
List<Account> accounts = new List<Account>() { new Account { Name = "Scrooge McDuck", Amount = 667377678765m }, new Account { Name = "Donald Duck", Amount = -200m }, new Account { Name = "Ludwig von Drake", Amount = 20000m }}; ImmutableList<Account> immutableAccounts = (); ImmutableList<Account>.Builder builder = (); for (int i = 0; i < ; i++) { Account a = builder[i]; if ( > 0) { (a); } } ImmutableList<Account> overdrawnAccounts = (); foreach (var item in overdrawnAccounts) { ("{0} {1}", , ); } public class Account { public string Name { get; set; } public decimal Amount { get; set; } }
Read-only collection (https:///article/) provides a read-only view of the collection. The collection can still be modified without accessing the collection using read-only views. And the set that can never be changed.
This is all about this article about the unchanging collection of C# collections. I hope it will be helpful to everyone's learning and I hope everyone will support me more.