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.
List<string> names=new List<string>(){"Rod", "Jane", "Freddy"}; Then you can say: ReadOnlyCollection<string> readOnlyNames=names. AsReadOnly();
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With