Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedList does not contain explicit Add method

Tags:

c#

I found interesting behavior of LinkedList<T>. I can't call Add method for an instance of LinkedList<>. However LinkedList<T> implements ICollection<T> (link) which actually has the Add method.

Here are examples. When I do like this, it works perfect:

ICollection<string> collection = new LinkedList<string>();
collection.Add("yet another string");

But this code even will not compile:

LinkedList<string> linkedList = new LinkedList<string>();
linkedList.Add("yet another string");

Compiler says: "Can not access explicit implementation of 'ICollection.Add' "Error CS1061 'LinkedList' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'LinkedList' could be found (are you missing a using directive or an assembly reference?)"

Moreover if to look at the sources of LinkedList, it implements the method. So my question is, how can it be?

like image 447
lowercase93 Avatar asked Jan 12 '16 16:01

lowercase93


2 Answers

The method is implemented explicitly as per the error message. That means an explicit cast to the given interface is required. In your second example this will work:

((ICollection<string>)linkedList).Add("yet another string");

For whatever reason using this technique the implementer of an interface may choose not to make certain interface methods and properties part of the class'es native, public interface.

In case of the LinkedList<T> class, the author apparently preferred a cannonical naming scheme for all possible types of 'add' functionality (i.e. AddFirst / AddLast (instead of plain Add) / AddBefore / AddAfter) over making the abstract collection interface directly accessible. However, thanks to explicit implementation compatibility with callers that expect an ICollection<T> is still maintained, and its Add is translated to an AddLast call which is logical in respet to ICollection<T>'s contract. (While the evaluation of such design decision is subjective, let me add I consider it a good thing.)

like image 176
Ondrej Tucny Avatar answered Nov 05 '22 21:11

Ondrej Tucny


The answer is in the compiler message: "You can not access explicit implementation methods"

If you look through the code you'll see that actually LinkedList implements the ICollection explictly.

You have to cast your object to ICollection in this way:

((ICollection<string>)linkedList).Add("yet another string");

Check these links for more reference:

  • MSDN for Explicit interface

  • Why use explicit interface implementation as a default implementation technique

like image 32
Martino Bordin Avatar answered Nov 05 '22 21:11

Martino Bordin