.NET Framework ReadOnlyCollections Updating 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 Extensions
> Step 2: And Like the video. BONUS: You can also share it!


A ReadOnlyCollection cannot be edited directly. Instead, the source collection is updated and the ReadOnlyCollection will reflect these changes. This is the key feature of the ReadOnlyCollection.

var groceryList = new List<string> { "Apple", "Banana" };

var readOnlyGroceryList = new ReadOnlyCollection<string>(groceryList);

var itemCount = readOnlyGroceryList.Count;  // There are currently 2 items

//readOnlyGroceryList.Add("Candy");         // Compiler Error - Items cannot be added to a ReadOnlyCollection object
groceryList.Add("Vitamins");                // ..but they can be added to the original collection

itemCount = readOnlyGroceryList.Count;      // Now there are 3 items
var lastItem = readOnlyGroceryList.Last();  // The last item on the read only list is now "Vitamins"

View Demo

Got any .NET Framework Question?