Creating a read-only collection from an array in C#
November 25, 2016 Leave a comment
The Array class has a number of interesting methods. One of them allows you to easily convert an array of T into a read-only collection of T:
string[] bands = new string[5] { "Queen", "ACDC", "Metallica", "Genesis", "INXS" }; IReadOnlyCollection<string> readOnlyBands = Array.AsReadOnly<string>(bands);
Note that readOnlyBands is, well, read-only, so there’s no Add or Remove method that otherwise are often available on lists.
View all various C# language feature related posts here.