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());
Overall, List is a concrete type that implements the IList interface.
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.
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 .
It implements IList<TheType> and not IList You need to check the generic type definitions for the interfaces.
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.
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 course
List` satisfies admirably.
So; this provides plenty of backwards compatibility with existing code and data-binding support via this.
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