3

I'm looking at LinkedList class implementation in C# and I cannot understand how Add method is hidden.

LinkedList implements ICollection which has an Add method. In the LinkedList class code the Add method is declared as:

void ICollection<T>.Add(T value);

How it is possible to have internal method which is declared in the interface?

mdm
  • 12,480
  • 5
  • 34
  • 53
Eugeniu Torica
  • 7,484
  • 12
  • 47
  • 62

1 Answers1

6

The interface is implemented explicitly.

Explicilty implemented interface members can only be accessed through an instance of the implemented interface, like so:

LinkedList list;
((ICollection)list).Add(...)

Check this SO question and answer for more information: implicit vs explicit interface implementation

Community
  • 1
  • 1
InBetween
  • 32,319
  • 3
  • 50
  • 90
  • Another good example of this in .NET are Streams. Most streams implement IDisposable, yet have a public method called "Close" instead of "Dispose". – vcsjones Jun 14 '11 at 10:23
  • Ok but when I have an interface and a class that implements that interface I cannot have a private method that implements interface nor I can miss interface's method from implementation. – Eugeniu Torica Jun 14 '11 at 10:24
  • @Jenea: You are not missing the method nor is it private. Think **why** you implement interfaces. You do it to certify that a given `class` will comply with a certain "contract". This is only useful if a consumer of said `class` will access it through an instance of the `interface` it implements (if the consumer were to have access to the `class` instance itself, why use the `interface`?). When accessing through the `interface`, the consumer has access to all methods defined by the `interface`, implicit or explicit. – InBetween Jun 14 '11 at 10:28