How to Convert List<string> to ReadOnlyCollection<string> in C#
Solution 1:
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
Solution 2:
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.
Solution 3:
The constructor of ReadOnlyCollection accepts an IList
Here is some reference http://msdn.microsoft.com/en-us/library/ms132476.aspx
var myreadonlycollection = new ReadOnlyCollection<string>(listname);
Solution 4:
var readonlyCollection = new ReadOnlyCollection<string>(list);