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?
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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With