Should I always return IEnumerable<T> instead of IList<T>?

Framework design guidelines recommend using the class Collection when you need to return a collection that is modifiable by the caller or ReadOnlyCollection for read only collections.

The reason this is preferred to a simple IList is that IList does not inform the caller if its read only or not.

If you return an IEnumerable<T> instead, certain operations may be a little trickier for the caller to perform. Also you no longer will give the caller the flexibility to modify the collection, something that you may or may not want.

Keep in mind that LINQ contains a few tricks up its sleeve and will optimize certain calls based on the type they are performed on. So, for example, if you perform a Count and the underlying collection is a List it will NOT walk through all the elements.

Personally, for an ORM I would probably stick with Collection<T> as my return value.


It really depends on why you are using that specific interface.

For example, IList<T> has several methods that aren't present in IEnumerable<T>:

  • IndexOf(T item)
  • Insert(int index, T item)
  • RemoveAt(int index)

and Properties:

  • T this[int index] { get; set; }

If you need these methods in any way, then by all means return IList<T>.

Also, if the method that consumes your IEnumerable<T> result is expecting an IList<T>, it will save the CLR from considering any conversions required, thus optimizing the compiled code.


In general, you should require the most generic and return the most specific thing that you can. So if you have a method that takes a parameter, and you only really need what's available in IEnumerable, then that should be your parameter type. If your method could return either an IList or an IEnumerable, prefer returning IList. This ensures that it is usable by the widest range of consumers.

Be loose in what you require, and explicit in what you provide.

Tags:

C#

Ienumerable