Creating a read-only collection from an array in C#

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.

Elliot Balynn's Blog

A directory of wonderful thoughts

HarsH ReaLiTy

A Good Blog is Hard to Find

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: