Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert List<string> to ReadOnlyCollection<string> in C#

I want to convert the items entered to a String list to:

System.Collections.ObjectModel.ReadOnlyCollection<string> 

I have tried using:

(System.Collections.ObjectModel.ReadOnlyCollection<string>)listname 

But it returns an error.

like image 228
techno Avatar asked Nov 15 '11 17:11

techno


People also ask

How do I convert a list to a readonly list?

List<string> names=new List<string>(){"Rod", "Jane", "Freddy"}; Then you can say: ReadOnlyCollection<string> readOnlyNames=names. AsReadOnly();

What is IReadOnlyCollection C#?

The IReadOnlyCollection interface extends the IEnumerable interface and represents a basic read-only collection interface. It also includes a Count property apart from the IEnumerable members as shown in the code snippet given below.

Is a readonly collection mutable?

The fact that ReadOnlyCollection is immutable means that the collection cannot be modified, i.e. no objects can be added or removed from the collection.


2 Answers

You can create a new instance using the existing List in the constructor.

var readOnlyList = new ReadOnlyCollection<string>(existingList); 

ReadOnlyCollection(Of T) Constructor on MSDN

like image 177
Balthy Avatar answered Oct 07 '22 10:10

Balthy


If you've got:

List<string> names=new List<string>(){"Rod", "Jane", "Freddy"};

Then you can say:

ReadOnlyCollection<string> readOnlyNames=names.AsReadOnly();

This doesn't copy the list. Instead the readonly collection stores a reference to the original list and prohibits changing it. However, if you modify the underlying list via names then the readOnlyNames will also change, so it's best to discard the writable instance if you can.

like image 32
Sean Avatar answered Oct 07 '22 08:10

Sean