Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison between List, IList, and IEnumerable

Tags:

c#

.net

I have a C# application in which I handle some collection types. I need to know what the differences between these types are:

  1. List
  2. IList
  3. IEnumerable

What are the differences for each one in comparison with the others?

like image 408
Lamloumi Afif Avatar asked Nov 23 '13 09:11

Lamloumi Afif


People also ask

What is difference between IList and List in C#?

The main difference between List and IList in C# is that List is a class that represents a list of objects which can be accessed by index while IList is an interface that represents a collection of objects which can be accessed by index.

What is the difference between ICollection and IList?

ICollection<T> is an interface that exposes collection semantics such as Add() , Remove() , and Count . Collection<T> is a concrete implementation of the ICollection<T> interface. IList<T> is essentially an ICollection<T> with random order-based access.

Is IEnumerable faster than List C#?

IEnumerable is conceptually faster than List because of the deferred execution. Deferred execution makes IEnumerable faster because it only gets the data when needed. Contrary to Lists having the data in-memory all the time.

What is the use of IEnumerable ICollection IList and IDictionary?

To begin with, all the interfaces (ICollection, IList, IQueryable, IDictionary) inherit from IEnumerable, which allows us to use the foreach statement.


1 Answers

  • IEnumerable<T> is the base interface that the following extend or implement. It doesn't allow for direct access and is readonly. So use this only if you intend to iterate over the collection.

  • ICollection<T> extendsIEnumerable<T> but in addition allows for adding, removing, testing whether an element is present in the collection and getting the total number of elements. It doesn't allow for directly accessing an element by index. That would be an O(n) operation as you need to start iterating over it until you find the corresponding element.

  • IList<T> extends ICollection<T> (and thus it inherits all its properties) but in addition allows for directly accessing elements by index. It's an O(1) operation.

  • List<T> is just a concrete implementation of the IList<T> interface.

In your code you should always expose the type that's highest in the object hierarchy that will correspond to the needs of the callers. So for example if the callers are only going to enumerate over the dataset, use IEnumerable<T>. If they need to have direct access to elements by index expose an IList<T>.

List<T> should only be used internally by your code but usually not present in the signature of the methods you are exposing. This gives you more flexibility as you could easily swap the concrete implementation without breaking the contract.

like image 180
Darin Dimitrov Avatar answered Sep 27 '22 20:09

Darin Dimitrov