skip to content

In C#, should a team's service methods return a lazy IEnumerable<T> LINQ query, a materialised List<T>, or an IReadOnlyList<T>, and how would you set that rule?

level: principalimportance: should knowfreq 40%

answer

  1. who decides when it runs
  2. laziness is invisible in the type
  3. snapshot versus live view
  4. streaming has a place
  5. make the rule checkable

basics

~20 s

Most teams make methods materialise query results and say so in the type, typically IReadOnlyList<T>, so callers get a snapshot they can count and enumerate twice. A lazy IEnumerable<T> is reserved for deliberate streaming and documented.

solid answer

~40 s

Returning `_orders.Where(o => o.IsOpen)` hands callers a query bound to private state: it runs on their schedule, sees later changes, re-runs on every enumeration, throws from their code, and throws `InvalidOperationException` if the owner writes to the list during their `foreach`. None of that is visible in the signature, because `IEnumerable<T>` looks the same whether it is lazy or a list. Materialising inside the method and returning `IReadOnlyList<T>` or `IReadOnlyCollection<T>` gives a stable snapshot with a cheap `Count`, paid once by the code that knows the cost. The price is memory and lost streaming when results are large or callers want only the first few. A workable rule: materialised read-only types by default; a lazy `IEnumerable<T>` only where streaming is the point, named and documented as single-pass; CA1851 enabled to catch the rest.

code

csharp · 28 lines
csharp
var book = new OrderBook();
book.Add(new Order(1, 250m));
book.Add(new Order(2, 900m));

IEnumerable<Order> lazy = book.LargeOrdersLazy();
IReadOnlyList<Order> snapshot = book.LargeOrdersSnapshot();
book.Add(new Order(3, 700m));
Console.WriteLine($"lazy sees {lazy.Count()}, snapshot holds {snapshot.Count}");

try
{
    foreach (var o in book.LargeOrdersLazy())
        book.Add(new Order(o.Id + 10, o.Total));  // the caller writes while the query reads
}
catch (InvalidOperationException ex)
{
    Console.WriteLine(ex.Message);
}

class OrderBook
{
    private readonly List<Order> _orders = [];
    public void Add(Order o) => _orders.Add(o);
    public IEnumerable<Order> LargeOrdersLazy() => _orders.Where(o => o.Total > 500m);
    public IReadOnlyList<Order> LargeOrdersSnapshot() => _orders.Where(o => o.Total > 500m).ToList();
}

record Order(int Id, decimal Total);

go deeper

for a junior

Recall that a method returning a LINQ query hands back something that runs later, while returning ToList() hands back results that already exist.

for a middle

Explain how a lazy return value re-runs, sees later changes and can throw in the caller's foreach, and why IReadOnlyList<T> signals a snapshot.

for a senior

Review service methods for leaked deferred queries, choose which ones must stream, and fix the others by materialising inside the method.

for a principal

Own the team rule: default return types for query results, the documented exception for streaming APIs, and the analyzer and review checks that enforce both.

## What a return type promises `IEnumerable<T>` is the weakest promise a method can make: "you can enumerate this". It says nothing about whether the elements already exist, whether enumerating twice is cheap, whether a second pass returns the same elements, or whether enumeration can fail. A method that returns a deferred LINQ query and one that returns a `List<T>` have the same signature when both are typed `IEnumerable<T>`, so the caller cannot tell them apart. That makes the return type of query-producing methods a **team decision**, not a local style choice. There is no single right answer, but the trade-offs are concrete. ## Three options compared | Returned | What the caller gets | Strengths | Risks | |---|---|---|---| | Lazy `IEnumerable<T>` (a deferred query) | a live view over the owner's data | no allocation until used; streams large results; caller can stop early | re-runs on every pass; sees later changes; throws in caller code; breaks if the owner writes mid-enumeration | | `List<T>` | a mutable snapshot | cheap `Count` and indexing; repeatable | caller can `Add` and `Remove`; signature invites mutation | | `IReadOnlyList<T>` or `IReadOnlyCollection<T>` (backed by a fresh list or array) | a read-only view of a snapshot | cheap `Count`; repeatable; type states it is materialised | allocation even when caller needs one element; no streaming | ## The case for materialising by default The example below shows the two failure modes of returning a lazy query from a class that owns a `List<Order>`: 1. A caller holds the lazy result while another order is added. Counting it later gives **2**, while the snapshot method's result still holds **1**. The lazy result is a view, not an answer. 2. A caller loops over the lazy result and, inside the loop, calls back into the service, which adds an order. The next step throws **`InvalidOperationException`: "Collection was modified; enumeration operation may not execute."** The failure appears in the caller's code, though the cause is the service's design. More reasons teams default to snapshots: - **Execution happens where the cost is understood.** The service decides when its filters, projections and lookups run, and runs them once. - **Exceptions surface inside the service**, near the code that can explain them, rather than in a caller's `foreach` much later. - **Callers can enumerate freely.** Counting and then looping, or passing the result to two consumers, does not repeat work or side effects. - **The type documents the guarantee.** `IReadOnlyList<T>` tells a reader the data exists and can be counted without enumerating. ## When a lazy sequence is the right contract - **The result is large or unbounded**, such as an export read row by row, and callers process it once from start to finish. - **Callers typically stop early**, and materialising everything would waste work. - **The sequence is a composable building block** inside one layer, where the same team writes both ends and enumerates once. - **The source is asynchronous I/O**, in which case the async sequence type covered with asynchronous sequences is the better contract than a synchronous lazy one. When a lazy result is chosen, it should be visible: a method name or documentation that says the result is streamed and should be enumerated once. ## Making the rule stick 1. **Write it down** in the team's coding conventions: query results crossing a class boundary are materialised and returned as `IReadOnlyList<T>` or `IReadOnlyCollection<T>`, unless the method is documented as streaming. 2. **Enable CA1851** at warning severity, so code that enumerates an `IEnumerable<T>` twice is flagged in builds and reviews. 3. **Prefer collection types in parameters** when a method needs to enumerate twice, so the obligation moves to the caller's type, not a comment. 4. **Add it to the review checklist**: a `return` of a `Where` or `Select` chain over a field is the pattern to question. 5. **Test with two enumerations** for methods that must be safe to re-enumerate. Two neighbouring decisions are separate. Whether returning `IQueryable<T>` from a repository is acceptable is a different question, covered with IQueryable and expression trees. How read-only interfaces and `ReadOnlyCollection<T>` wrappers protect a private list is covered with the read-only collection interfaces. ## Summary - `IEnumerable<T>` hides whether a result is a live query or a snapshot. - Lazy results move execution, exceptions and consistency problems into the caller. - A materialised `IReadOnlyList<T>` is the common default; lazy sequences are a deliberate, documented exception for streaming. - Back the rule with CA1851, parameter types and review habits.

  • If a method returns a fresh List<T> typed as IReadOnlyList<T>, can callers still modify it, and does it matter?
    A caller can cast back to `List<T>` and call `Add`, but the list was built for that call, so only the caller's own copy changes and the service is unaffected. The risk is different when a method returns its private field typed as `IReadOnlyList<T>`: a cast then mutates the owner's state. Wrapping with `AsReadOnly()` closes that gap, a topic covered with the read-only collection interfaces.
  • How should a method that streams a very large result be designed if laziness is chosen?
    Make the laziness explicit. Name or document the method as streaming, state that the result should be enumerated once, and keep the source it reads from stable for the duration, or open the source inside the iteration so each pass is self-contained. Callers then consume it in a single `foreach` or pipe it into another streaming stage, and CA1851 helps catch accidental second passes. For I/O-bound sources, an asynchronous sequence is usually the better contract.

  • Returning IEnumerable<T> is always best because it is the most flexible type
  • An IEnumerable<T> return type tells callers the data is already in memory
  • A lazy query returned from a service is a snapshot of that moment
  • Materialising every result is free, so always call ToList()
  • A read-only interface type alone makes the elements immutable