8

ReadOnlyCollection<T> realises the ICollection<T> interface which has methods like Add and Remove. I know how to hide methods from Intellisense using attributes, but how is it possible to cause an actual compilation error if I try to use these methods?

(Btw, I know it doesn't make sense to call Add and Remove on a ROC, it's a question on causing compilation error for inherited memebers, not on using the correct data structure).

RichK
  • 11,318
  • 6
  • 35
  • 49

2 Answers2

18

They're implemented with explicit interface implementation, like this:

void ICollection<T>.Add(T item) {
    throw NotSupportedException();
}

The method is still callable, but only if you view the object as an ICollection<T>. For example:

ReadOnlyCollection<int> roc = new ReadOnlyCollection<int>(new[] { 1, 2, 3 });
// Invalid
// roc.Add(10);

ICollection<int> collection = roc;
collection.Add(10); // Valid at compile time, but will throw an exception
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Indeed, by implementing those methods from the ICollection<T> interface explicitly, you cannot call them directly.
You'll have to cast the object (the ReadOnlyCollection instance) to ICollection<T> explicitly. Then, you can call the Add method. (Hence, the compiler won't complain, although you'll get a runtime exception).

Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154