Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IList<T> vs IEnumerable<T>. What is more efficient IList<T> or IEnumerable<T>

Tags:

c#

.net

c#-4.0

What is more efficient way to make methods return IList<T> or IEnumerable<T>?

IEnumerable<T> it is immutable collection but IList<T> mutable and contain a lot of useful methods and properties.

To cast IList<T> to IEnumerable<T> it is just reference copy:

IList<T> l = new List<T>();
IEnumerable<T> e = l;

To cast IEnumerable<T> to List<T> we need to iterate each element or to call ToList() method:

IEnumerable<T>.ToList(); 

or may pass IEnumerable<T> to List<T> constructor which doing the same iteration somewhere within its constructor.

List<T> l = new List<T>(e);

Which cases you think is more efficient? Which you prefer more in your practice?

like image 646
angularrocks.com Avatar asked Aug 21 '10 06:08

angularrocks.com


People also ask

What's the difference between IEnumerable T and list t?

IEnumerable is read-only and List is not. IEnumerable types have a method to get the next item in the collection. It doesn't need the whole collection to be in memory and doesn't know how many items are in it, foreach just keeps getting the next item until it runs out.

Why we use IEnumerable instead of list?

IEnumerable is best to query data from in-memory collections like List, Array etc. IEnumerable doesn't support add or remove items from the list. Using IEnumerable we can find out the no of elements in the collection after iterating the collection. IEnumerable supports deferred execution.

What should I return IEnumerable or IList?

Generally, it's better to return IEnumerable<T> , as long as that has everything the caller needs.

Which is better IEnumerable or IList?

You use IEnumerable when you want to loop through the items in a collection. IList is when you want to add, remove, and access the list contents out of order.


1 Answers

As far as efficiency is concerned both are interfaces so the efficiency will depend on the actual concrete class you are returning. 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>. If the consumers of the class need to add elements, access elements by index, remove elements you are better off using an IList<T>.

So as always in programming: it depends :-)

like image 72
Darin Dimitrov Avatar answered Sep 17 '22 14:09

Darin Dimitrov