.NET Framework ReadOnlyCollections

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!

Remarks

A ReadOnlyCollection provides a read-only view to an existing collection (the 'source collection').

Items are not directly added to or removed from a ReadOnlyCollection. Instead, they are added and removed from the source collection and the ReadOnlyCollection will reflect these changes to the source.

The number and order of elements inside a ReadOnlyCollection cannot be modified, but the properties of the elements can be and the methods can be called, assuming they are in scope.

Use a ReadOnlyCollection when you want to allow external code to view your collection without being able to modify it, but still be able to modify the collection yourself.

See Also

  • ObservableCollection<T>
  • ReadOnlyObservableCollection<T>

ReadOnlyCollections vs ImmutableCollection

A ReadOnlyCollection differs from an ImmutableCollection in that you cannot edit an ImmutableCollection once you created it - it will always contain n elements, and they cannot be replaced or reordered. A ReadOnlyCollection, on the other hand, cannot be edited directly, but elements can still be added/removed/reordered using the source collection.



Got any .NET Framework Question?