8

Today I came across a dilemma what is the difference between ReadOnlyCollection<T> and ReadOnlyCollectionBuilder<T> in .Net?

In ReadOnlyCollection<T> object we cannot add and remove items.

Where as in ReadOnlyCollectionBuilder<T> object we can add and remove items.

If we can add and remove items in ReadOnlyCollectionBuilder<T> object, then why the name readonly?

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
Dharmesh Tailor
  • 320
  • 1
  • 11

1 Answers1

16

As per the documentation, ReadOnlyCollectionBuilder is just a builder for read-only collections. The idea is that the builder is mutable, but would only be used in a small scope. You'd create a builder, add a load of elements, then call ToReadOnlyCollection to efficiently create a read-only view on the data. (This resets the builder, so you avoid the possibility of mutating the read-only collection after creation.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194