Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how List<T> does not implement Add(object value)?

I believe it's pretty stupid, and I am a bit embarrassed to ask this kind of question, but I still could not find the answer:

I am looking at the class List<T> , which implemetns IList.

public class List<T> : IList

one of the methods included in Ilist is

int Add(object value)

I understand that List<T> should not expose that method (type safety...), and it really does not. But how can it be? mustnt class implement the entire interface?

like image 597
ET. Avatar asked Dec 08 '10 14:12

ET.


People also ask

Why does adding a new value to List <> overwrite previous values in the list <>?

Essentially, you're setting a Tag's name to the first value in tagList and adding it to the collection, then you're changing that same Tag's name to the second value in tagList and adding it again to the collection. Your collection of Tags contains several references to the same Tag object!

Does List implement IList?

Overall, List is a concrete type that implements the IList interface.

How do you add to a list only items that are not already in the list C#?

To implement the "add if not exists" method using IEnumerable: Use Contains on the IEnumerable to check if the item exists in the list. If Contains is false, use Append on the IEnumerable to add the item. Use a new variable to store the returned value because Append creates a new collection.


1 Answers

I believe that this (interface) method is implemented explicitly:

public class List<T> : IList
{
     int IList.Add( object value ) {this.Add((T)value);}
}

By doing so, the Add( object ) method will by hidden. You'll only able to call it, if you cast the List<T> instance back to an IList instance.

like image 178
Frederik Gheysels Avatar answered Nov 02 '22 04:11

Frederik Gheysels