What's the difference between IEnumerable and Array, IList and List?

IEnumerable provides only minimal "iterable" functionality. You can traverse the sequence, but that's about it. This has disadvantages -- for example, it is very inefficient to count elements using IEnumerable, or to get the nth element -- but it has advantages too -- for example, an IEnumerable could be an endless sequence, like the sequence of primes.

Array is a fixed-size collection with random access (i.e. you can index into it).

List is a variable-size collection (i.e. you can add and remove elements) with random access.

IList is an interface which abstracts list functionality (count, add, remove, indexer access) away from the various concrete classes such as List, BindingList, ObservableCollection, etc.


IEnumerable is an interface that allows the iteration through a collection of items (e.g. via the foreach keyword).

An array is a .NET intrinsic. It holds items of the same type, but it is of a fixed size. Once you create an array with x elements, it cannot grow or shrink.

IList defines the interface for a list, and also implements IEnumerable.

List implements the IList interface; it is a concrete type of list.

The difference between .NET Lists and arrays is that lists can have elements added to them -- they grow to be big enough to hold all of the required items. The list stores this internally in an array and, when the array is no longer big enough to hold all of the elements, a new array is created and the items copied across.

IList & arrays both implement IEnumerable. That's how interfaces work -- classes implement the contract and behave in a similar fashion and can be treated similarly as a result (you know that the class implements IEnumerable, you don't need to know the hows or the whys). I suggest you read up on interfaces and so forth.


IEnumerable and IList are interfaces. Array and List are classes. Array implements IEnumerable. List implements IList which extends IEnumerable.

Edit: as itowlson mentionned in a comment, Array also implements IList.

Tags:

C#