Sunday, December 14, 2008

C# - Hiding interface methods (How and Why)

In my attempt to create a "Generic Object Reference Implementation" (I talked about this in a previous post here) version of System.Collections.Generic.LinkedList I needed to implement the ICollection<T> interface.

Well, you will notice that the Frameworks' LinkedList implementation has four methods to add a node: AddFirst, AddBefore, AddAfter and AddLast. Yet, ICollection<T> demands that we have another method called Add.

But, LinkedList does not have and Add method.

And, LinkedList does implement the ICollection<T> interface.


Well, after some searching and a Usenet post, I found out how it is done.

It is called Implementing the interface method EXPLICITLY for the interface. This is accomplished by placing the name of the interface before the method name, as such:


The method Add will now will be only available when the class is cast as ICollection<T>. This gives us the best of both worlds, we get the benefit of implementing ICollection<T> without having to expose a method that may not make sense in the context of the class.

No comments: