Search code examples
c#interfacereadonly-collection

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


Solution

  • 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