Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why List<> implements IList [duplicate]

Possible Duplicate:
Why does (does it really?) List implement all these interfaces, not just IList?

Out of curiosity, what is the reason behind generic List<> implementing non-generic interface IList?

Sample code

IList<int> list = new List<int>();
list.Add(1);

//compiles but ArgumentException thrown at run time
((IList)list).Add(new object()); 
like image 952
oleksii Avatar asked May 27 '11 17:05

oleksii


People also ask

Does list implement IList?

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

Does array implement IList?

Definition of IList interface is "Represents a non-generic collection of objects that can be individually accessed by index.". Array completely satisfies this definition, so must implement the interface.

Does list implement IEnumerable?

List implements IEnumerable, but represents the entire collection in memory. LINQ expressions return an enumeration, and by default the expression executes when you iterate through it using a foreach, but you can force it to iterate sooner using .

Does Observablecollection implement IList?

It implements IList<TheType> and not IList You need to check the generic type definitions for the interfaces.


2 Answers

Take a look at this blog post by Eric Lippert: So many interfaces. He has some great insights, as always

Make sure to read the whole thing, but here's the quote that answers the question:

Why then does List implement IList?

It is a bit odd, since List for any type other than object does not fulfill the full contract of IList. It's probably to make it easier on people who are updating old C# 1.0 code to use generics; those people were probably already ensuring that only the right types got into their lists. And most of the time when you're passing an IList around, it is so the callee can get by-index access to the list, not so that it can add new items of arbitrary type.

like image 177
Dyppl Avatar answered Sep 17 '22 15:09

Dyppl


IList has particular significance. In particular, it forms the hub of much data-binding, and largely acts as the canonical way of saying "I'm a bunch of items".

Note also - generics are not convenient via reflection; data-binding struggles a bit with them, preferring non-generic APIs. It helps that in the binding scenario, the convention used by the data-binding code is that if the list also has a non-object indexer:

public SomeType this[int index] {get;}

then assume the items are SomeType. Which of courseList` satisfies admirably.

So; this provides plenty of backwards compatibility with existing code and data-binding support via this.

like image 40
Marc Gravell Avatar answered Sep 18 '22 15:09

Marc Gravell