How to hide some members of an interface

nan picture nan · Mar 12, 2011 · Viewed 13.9k times · Source

I would like to create a custom collection that implements ICollection.

But I would like not to expose some memebers of ICollection like Clear method.

How to achieve this?

Answer

Jaroslav Jandek picture Jaroslav Jandek · Mar 12, 2011

You can implement the interface explicitly and have the implementation hidden:

public class UrClass : ICollection
{
    void ICollection.Clear() { ... }
}

The user can't call urClassInstance.Clear() directly, but they can call ((ICollection)urClassInstance).Clear() indirectly like this.