1

Possible Duplicate:
When to use IList and when to use List

This question could just be a lack of understanding of the .NET framework, but what is the benefit of actually having a set of data in an interface rather than just having it in a list? Up to this point I have only used List<T> and it seems to do pretty much what I need it to do, but looking at other peoples code I see that it is quite frequent for someone to use IEnumerable<T>, IQueryable/IQueryable<T>, ICollection<T>, and even IList<T>. That being said, what is even the difference between List<T> and IList<T>?

I understand that some of them have different functionality on the contained objects, but which is the most safest to go with? IEnumerable?

Community
  • 1
  • 1
Brandon Clapp
  • 66,931
  • 6
  • 20
  • 24
  • 1
    It's good practise to use only what you need. So if a method does only use methods and properties of `IList`, why should it enforce a `List` as parameter? Note that an `Array` also implements `IList`. – Tim Schmelter Jan 11 '13 at 13:43

1 Answers1

3

If you set the type to an interface type, you can use any type that implements IList<T>.

If you use List<T> you can only use that type and types that inherit from it.

It depends on usage - if you only need to iterate, use IEnumerable<T>, if you also need to add/remove items, use ICollection<T>. If you need to index into the collection, use IList<T>, etc...

Oded
  • 489,969
  • 99
  • 883
  • 1,009