.NET Framework ReadOnlyCollections Creating a ReadOnlyCollection

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Using 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.



Got any .NET Framework Question?