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);
Additionaly, LINQ provides an AsReadOnly()
extension method for IList
objects:
var readOnlyVersion = groceryList.AsReadOnly();
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
.