1

I'm designing some interfaces to use ReadOnlyCollection<T> to indicate that consumers of those interfaces can only read from the collection.

The collection supplied however isn't immutable, and will change from time to time, and I'm wondering if I'm having a wrong design. Should children of a ReadOnlyCollection<T> be immutable as well?

Aidiakapi
  • 6,034
  • 4
  • 33
  • 62
  • 2
    http://blog.slaks.net/2013-06-11/readonly-vs-immutable/ http://stackoverflow.com/a/17012351/34397 – SLaks Jun 17 '13 at 18:11
  • 1
    @SLaks Thanks, but I know the difference between the two very well (the reason why I'm asking this). Someone told me that my `ReadOnlyCollection` should be immutable, and I thought there wasn't any reason for it to be, hence I just wanted to double check before having to refactor my library :). – Aidiakapi Jun 17 '13 at 20:49

1 Answers1

7

The ReadOnlyCollection<T> class is not intended to provide an immutable collection, but rather a "read only" wrapper around a mutable list. The underlying list is still always mutable, though, and changes to the list will be exposed to the read only collection.

If you need to expose a truly immutable collection in your design, you should consider using the new Immutable Collections for .NET, and expose the appropriate immutable collection.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Thanks! Those new collections seem interesting and very useful, however I do not need immutability (I actually depend on the mutability). – Aidiakapi Jun 17 '13 at 20:51
  • 1
    I don't like some of the interface names, though; IMHO, most of the `IReadOnlyXX` should have been `IReadableXX`. If I were in charge of naming, I would suggest that part of the contract of `IReadOnlyXX` should be that it should be safe to exchange references without having to wrap them in a `ReadOnlyCollection` or similar wrapper first. I'd also define an `IImmutableXX` interface, whose contract should be that persisting the reference be equivalent to persisting the contents; I'd have that be an interface to allow for things like... – supercat Jul 02 '13 at 15:14
  • ...a `FunctionToList` class whose constructor takes a `Func` along with an `int` (for the size), so a `new FunctionToList( (int n) => 1.0/(1+n), 1000000)` would behave like a list that would always holding the first million values {1, 1/2, 1/3, 1/4, ... 1/1,000,000}, but wouldn't actually have to store any of them. – supercat Jul 02 '13 at 15:17