Converting from ReadOnlyCollection to List

In the project I’m working on we use Generic Lists and ReadOnlyCollections wherever possible. Up until now, we’ve only ever had to convert from a List to a ReadOnlyCollection, which is achieved easily thanks to the AsReadOnly method:

MyList As New List(Of MyObject)
Dim MyReadOnlyCollection As ReadOnlyCollection(Of MyObject) = MyList.AsReadOnly
Today was the first time we had to go the other way around – from a ReadOnlyCollection to a List. Thanks to one of my Readify buddies (Geoff Appleby), I have learnt that it’s almost as easy, but maybe not as obvious. In fact, it had me stumped for a "short while" as I tried all kind of stuff to no avail.
The answer lies in the combination of the generic List object accepting a Collection object as one of its constructor overloads, and the implementation of ReadOnlyCollection. Because ReadOnlyCollection implements the IEnumerable interface, it can be passed into the List Constructor as a collection object. That means, it’s as simple as this:
Dim MyList2 As New List(Of MyObject)(MyReadOnlyCollection)
Hopefully, this might help someone else avoid spending time.
C# equivalents of the above:
List<MyObject> myList = new List<MyObject>();
ReadOnlyCollection<MyObject> myReadOnlyCollection = myList.AsReadOnly();

<MyObject> myList2 = new List<MyObject>(myReadOnlyCollection);
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s