Search code examples
c#.netilistgeneric-list

Why List<> implements IList


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()); 

Solution

  • 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.