2.1 — IEnumerable vs ICollection vs IList vs IQueryable¶
← Roadmap · Section: 2. Collections, LINQ and Async Prev: 1.26 Modern C# by version · Next: 2.2 Collections and Big-O
Markers: 🔥 ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- They form a ladder. Each one adds abilities to the one below it:
IEnumerable→ICollection→IList. IEnumerable<T>only lets you walk forward through items, one at a time. That is all.IQueryable<T>is the odd one out. It looks likeIEnumerablebut it builds a database query instead of looping in memory. Confusing the two is the single most expensive mistake in this topic.
The concept¶
Think of these as job descriptions for a collection. Each one says "here is what you are allowed to do with me".
You pick the smallest one that does the job. If your method only needs to loop through
items, ask for IEnumerable<T>. Asking for List<T> when you only loop means callers
have to give you a real list — they cannot hand you the results of a database query or a
lazily generated sequence.
There is one important twist. Three of these four are about collections in memory. The
fourth, IQueryable<T>, is about a query that has not run yet — usually against a
database. It shares the same shape but does something completely different underneath, and
that difference costs real money in real applications.
How it works¶
The ladder¶
IEnumerable<T> // walk forward through items. That is it.
↓ adds
ICollection<T> // + Count, Add, Remove, Clear, Contains
↓ adds
IList<T> // + access by position: list[0], Insert, IndexOf
Each level can do everything the level above it can, plus more.
IEnumerable<T> — the smallest. One job: give me items one at a time.
public interface IEnumerable<out T>
{
IEnumerator<T> GetEnumerator(); // that is the whole interface
}
That single method is what makes foreach work. Notice there is no Count, no Add, no
indexing. You cannot ask "how many?" without walking the whole thing.
IEnumerable<Order> orders = GetOrders();
foreach (var o in orders) { } // allowed
var n = orders.Count(); // allowed, but this is a LINQ method
// that WALKS EVERYTHING to count
var first = orders[0]; // NOT allowed — no indexer
orders.Add(newOrder); // NOT allowed — read-only
ICollection<T> — adds size and modification.
ICollection<Order> orders = new List<Order>();
orders.Count; // a real property — instant, no walking
orders.Add(newOrder);
orders.Remove(oldOrder);
orders.Contains(someOrder);
orders.Clear();
orders[0]; // still NOT allowed — no position access
IList<T> — adds position.
IList<Order> orders = new List<Order>();
orders[0]; // now allowed
orders.Insert(2, order);
orders.IndexOf(order);
The read-only versions — IReadOnlyCollection<T> and IReadOnlyList<T> — do the same
but with no Add or Remove. Use these when returning data you do not want callers
changing. See the Code section.
The one that is different: IQueryable<T>¶
IQueryable<T> inherits from IEnumerable<T>, so it looks interchangeable. It is not.
What happens when you call .Where(...) |
|
|---|---|
IEnumerable<T> |
Loops through the items in memory and tests each one with your C# code |
IQueryable<T> |
Builds up a description of the query. Nothing runs yet. When you finally ask for results, it is translated into SQL and sent to the database |
Here is why that matters enormously:
// IQueryable — the filter is TRANSLATED INTO SQL
IQueryable<Order> query = db.Orders;
var big = query.Where(o => o.Total > 1000).ToList();
// SQL sent: SELECT * FROM Orders WHERE Total > 1000
// The database does the filtering. Maybe 12 rows come back.
// IEnumerable — the filter happens in YOUR APPLICATION
IEnumerable<Order> all = db.Orders.ToList(); // ← ToList() runs the query NOW
var big = all.Where(o => o.Total > 1000).ToList();
// SQL sent: SELECT * FROM Orders
// ALL ten million rows travel across the network,
// then C# throws away the ones you did not want.
Same-looking code. One returns 12 rows, the other downloads your entire table.
And the trap is how easy it is to do by accident. This method signature causes it:
public IEnumerable<Order> GetOrders() => db.Orders;
// ^^^^^^^^^^^^^^^^^^ declaring the return as IEnumerable
// silently turns off SQL translation for every caller
The moment the return type is IEnumerable<T>, any .Where() a caller adds runs in
memory, not in the database. Nothing warns you. The code works — it is just catastrophically
slower as data grows.
More on this in 2.7 and 13.10.
Code¶
Rule of thumb: accept the smallest, return the most useful.
// PARAMETERS — ask for the least you need.
// IEnumerable accepts a List, an array, a HashSet, a LINQ result, anything.
public decimal CalculateTotal(IEnumerable<OrderLine> lines)
=> lines.Sum(l => l.Price * l.Quantity);
// If you need the count or to loop more than once, ask for IReadOnlyCollection.
// This signature DOCUMENTS that you will enumerate more than once.
public string Summarise(IReadOnlyCollection<Order> orders)
=> $"{orders.Count} orders, {orders.Sum(o => o.Total):C} total";
// RETURN TYPES — return something concrete enough to be useful,
// but not something callers can modify by accident.
public IReadOnlyList<OrderDto> GetRecent()
{
return _db.Orders
.Where(o => o.CreatedAt > DateTime.UtcNow.AddDays(-7)) // runs as SQL
.Select(o => new OrderDto(o.Id, o.Total))
.ToList(); // execute HERE, inside the method that owns the DbContext
}
Two deliberate choices in that method, both worth explaining in an interview:
.ToList()before returning. The query runs while theDbContextis still alive. If you returned theIQueryableinstead, the caller might enumerate it after the context has been disposed at the end of the request — which throws.IReadOnlyList<T>notList<T>. Callers can index and count it, but cannotAddto the collection you handed back. It states that this is a snapshot, not a live list.
Interview questions¶
Q: What is the difference between IEnumerable and IList?
They are two rungs of the same ladder. IEnumerable<T> is the smallest possible contract —
it only lets you walk forward through the items one at a time, which is what foreach
needs. It has no Count, no indexer, and no way to add or remove. IList<T> builds on it
through ICollection<T>, adding Count, Add, Remove, and access by position. As a
rule I take IEnumerable<T> as a parameter so callers can pass anything, and only ask for
something bigger when I genuinely need to count items or index into them.
Q: What is the difference between IEnumerable and IQueryable?
This is the important one. IEnumerable<T> does its work in memory using your compiled C#
code — calling Where on it loops through objects and tests each one. IQueryable<T>
instead builds up a description of the query as an expression tree, and when you finally ask
for the results, a provider like EF Core translates that into SQL and the database does the
work. So with IQueryable your filter becomes a WHERE clause, and with IEnumerable the
whole table is pulled across the network first and filtered afterwards.
Q: What goes wrong if you return IEnumerable<T> from a repository method?
You silently lose SQL translation. The moment the type is IEnumerable<T>, any Where or
OrderBy a caller adds runs in memory rather than in the database — so the query becomes
SELECT * over the whole table and the filtering happens after everything has already been
transferred. Nothing errors and it works fine on a test database with fifty rows, which is
why it usually reaches production before anyone notices. My preference is to execute inside
the repository with ToList() and return IReadOnlyList<T>, so nobody can accidentally
compose onto a query that has already left its context.
Q: When would you return IReadOnlyList<T> instead of List<T>?
Almost always, for anything crossing a boundary. Returning List<T> hands the caller a
live, mutable reference to your data — they can add or remove items and, if you cached that
list, you have just let them corrupt your cache. IReadOnlyList<T> still gives them
counting and indexing but no mutation, and it communicates that they are looking at a
snapshot.
Traps ⚠️¶
- Returning
IEnumerable<T>from a data access method kills SQL translation. Filters then run in memory over the full table. .Count()on anIEnumerablewalks the entire sequence..Counton anICollectionis an instant property. The one-character difference matters.- Enumerating an
IEnumerabletwice may run the work twice. For a database query that is two round trips. See 2.6. IReadOnlyList<T>is not a security guarantee. A caller can cast back toList<T>. It communicates intent; it does not enforce it. UseImmutableList<T>if you need real enforcement.- Returning an
IQueryableout of a repository leaks the database into your business logic — and it can be enumerated after theDbContextis disposed. IEnumerable<T>is covariant (out T),IList<T>is not. SoIEnumerable<Dog>works whereIEnumerable<Animal>is expected, butIList<Dog>does not. See 1.10.
Related¶
- 2.2 Collections and Big-O — the concrete types behind these interfaces
- 2.6 Deferred execution — why enumerating twice is dangerous
- 2.7 Expression trees — how
IQueryablebecomes SQL - 1.10 Generics — covariance on
IEnumerable<out T> - 13.10 Client vs server evaluation — the same trap in EF Core
- 13.19 Repository pattern — what to return from a repository