Creating a ReadOnlyCollection
suggest changeUsing the Constructor
A ReadOnlyCollection is created by passing an existing IList object into the constructor:
var groceryList = new List<string> { "Apple", "Banana" };
var readOnlyGroceryList = new ReadOnlyCollection<string>(groceryList);
Using LINQ
Additionaly, LINQ provides an AsReadOnly() extension method for IList objects:
var readOnlyVersion = groceryList.AsReadOnly();
Note
Typically, you want to maintain the source collection privately and allow public access to the ReadOnlyCollection. While you could create a ReadOnlyCollection from an in-line list, you would be unable to modify the collection after you created it.
var readOnlyGroceryList = new List<string> {"Apple", "Banana"}.AsReadOnly();
// Great, but you will not be able to update the grocery list because
// you do not have a reference to the source list anymore!
If you find yourself doing this, you may want to consider using another data structure, such as an ImmutableCollection.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents