LinkedList does not contain an explicit Add method

I found an interesting behavior LinkedList<T>. I cannot call the Add method on the LinkedList <> instance. However, LinkedList<T>implements ICollection<T>( link ), actually has an Add method.

Here are some examples. When I like it, it works great:

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

But this code will not even compile:

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

The compiler says: “Unable to access the explicit implementation of“ ICollection.Add ”“ Error CS1061 “LinkedList” does not contain a definition for “Add”, and the “Add” extension method cannot be found that takes the first argument of type “LinkedList” (you missing using directive or assembly reference?) "

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

+4
source share
3 answers

The method is implemented explicitly in accordance with the error message. This means that explicit casting to this interface is required. In your second example, this will work:

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

For any reason, using this method, the interface designer may choose not to use certain interface methods and properties in the class’s own, public interface.

LinkedList<T> , -, "" (.. AddFirst/AddLast ( plain Add)/AddBefore/AddAfter), . , , ICollection<T> , Add AddLast, ICollection<T> . ( , , .)

+4

: " "

, , LinkedList ICollection.

ICollection :

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

:

+1

LinkedList .

Use the AddLast method of LinkedList or use the ICollection interface (instancing as it or casting), which implements the Add method as AddLast in the highest degree.

0
source

Source: https://habr.com/ru/post/1623962/


All Articles