Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ReadOnlyCollection hide Add and Remove methods

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).

like image 431
RichK Avatar asked Nov 08 '10 07:11

RichK


2 Answers

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
like image 96
Jon Skeet Avatar answered Oct 18 '22 19:10

Jon Skeet


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).

like image 29
Frederik Gheysels Avatar answered Oct 18 '22 20:10

Frederik Gheysels