I am a huge fan of read only/immutable collections and data. Hopefully the increased exposure through the blogosphere alerted users to the advantages of this type of programming for the appropriate scenarios. I wanted to discuss [ReadOnlyCollection
It implements IList
[IList
Unfortunately there is not a good interface to implement. The indexable interfaces are all representative of mutable collection types. It would be nice to add an immutable/read only interface which can be safely implemented.
interface IReadOnlyList<T> : IEnumerable<T>
{
T this[int index] { get; }
int Count { get; }
int IndexOf(T value);
bool Contains(T item);
void CopyTo(T[] array, int arrayIndex);
}
Ideally this would be called IImmutableList
It’s not deeply ReadOnly
ReadOnlyCollection
Take the following sample which uses a ReadOnlyCollection to wrap a List.
var list = new List<int>();
list.AddRange(Enumerable.Range(1, 10));
var roList = new ReadOnlyCollection<int>(list);
Console.WriteLine(roList.Count); // Outputs: 10
list.Add(42);
Console.WriteLine(roList.Count); // Outputs: 11
There are ways to avoid this problem with ReadOnlyCollectionn. The simplest is to make sure you pass a copy of your list into the constructor.
var roList2 = new ReadOnlyCollection<int>(new List<int>(list));