Wow, it's been a whole 7 days since my last post - some weeks just fly by way to quickly. Especially when some deadline is looming. Funny, that.
Anyways, I thought I would show a neat technique you can use if you'd like to implement an interface, but not support some of its members. A good example of this is the ReadOnlyCollection. It's a collection - but an immutable one, and thus doesn't support the Add and Remove members it inherits from ICollection. In fact, those methods doesn't even seem to be members of the class - they dont show up in intellisense for example:
But we know they have to be there, cause it implements the interface in which they're defined:
So whats going on here? How can they get away with that? The trick is implementing (one or more of) the members of the interface explicitly. Normally, you would implement the interface members implicitly - meaning you just include a public member in your class with the same name as the one in the interface. When you implement the interface member explicitly, you qualify it with the interface type:
void ICollection<T>.Add(T item)
{
// do stuff..
}
And when you do that, you're allowed to change the access modifier - so you can effectively implement a member of a public interface as private, thus hiding it from the consumer of your class.
Obviously, if the consumer was to cast your class to the type of the interface, he would be able to access the member - so you cannot rely on this to make sure the method never gets called by anone. The way to do that, is by making the member throw a NotSupportedException - which is what a ReadOnlyCollection<T> will do if you cast it to ICollection<T> and try to invoke the Add or Remove methods. Hiding it may sometimes be a good idea aswell though - to remove the clutter from intellisense if nothing else :)