What is the difference between IEnumerable and IList?

 Posted by Bh80prk on 12/21/2012 | Category: C# Interview questions | Views: 4814 | Points: 40


IEnumerable<T> represents a series of items that you can iterate over (using foreach, for example)
IEnumerable doesn't have the Count method and you can't access the collection through an index (although if you are using LINQ you can get around this with extension methods).
IEnumerable is a general-purpose interface that is used by many classes, such as Array, List and String in order to let someone iterate over a collection. Basically, it's what drives the foreach statement.
As a rule of thumb you should always return the type that's highest in the object hierarchy that works for the consumers of this method. In your case IEnumerable<T>.


IList<T> is a collection that you can add to or remove from.
List has count method and accessed using index.
IList is typically how you expose variables of type List to end users. This interface permits random access to the underlying collection.
If the consumers of the class need to add elements, access elements by index, remove elements you are better off using an IList<T>.

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response