In C#, what may a caller do through IEnumerable<T>, ICollection<T>, IList<T>, IReadOnlyCollection<T> and IReadOnlyList<T>, and which should a parameter use?
answer
- two ladders over one base
- Count and indexer, no Add
- mutators start at ICollection<T>
- accept the least you use
- the ladders never meet
basics
~10 sIEnumerable<T> only enumerates; IReadOnlyCollection<T> adds Count; IReadOnlyList<T> adds a get-only indexer; ICollection<T> adds Count, Add, Remove and Clear; IList<T> adds an indexer setter, Insert and RemoveAt. A parameter takes the least its method uses.
solid answer
~40 sThe interfaces form two ladders over `IEnumerable<T>`. The read-only ladder: `IReadOnlyCollection<T>` adds `Count`, and `IReadOnlyList<T>` adds a get-only indexer. The mutable ladder: `ICollection<T>` adds `Count`, `IsReadOnly`, `Add`, `Remove`, `Clear`, `Contains` and `CopyTo`, and `IList<T>` adds a settable indexer, `IndexOf`, `Insert` and `RemoveAt`. `List<T>` and arrays implement both ladders, but the ladders are unrelated: `IList<T>` does not derive from `IReadOnlyList<T>`, so an `IList<T>` variable passed to an `IReadOnlyList<T>` parameter fails with CS1503. A read-only interface limits what the caller can do through that reference; it does not promise that the collection never changes. For a parameter, take the least the method uses: `IEnumerable<T>` to loop, `IReadOnlyCollection<T>` when it also needs `Count`, `IReadOnlyList<T>` for indexed reads, and a mutable interface only when the method is meant to change the caller's collection.
code
csharp · 18 linesint[] seats = { 3, 1, 2 };
var waitlist = new List<string> { "Ana", "Ben" };
Console.WriteLine(Describe(seats));
Console.WriteLine(Describe(waitlist));
Console.WriteLine(Total(new HashSet<int> { 4, 5 }));
// Needs Count and an index: IReadOnlyList<T> accepts arrays and List<T>
static string Describe<T>(IReadOnlyList<T> items) =>
items.Count == 0 ? "empty" : $"{items.Count} items, first {items[0]}";
// Only loops: IEnumerable<T> accepts any sequence, HashSet<T> included
static int Total(IEnumerable<int> values)
{
var sum = 0;
foreach (var v in values) sum += v;
return sum;
}go deeper
Recall the members each interface adds: Count on the collection interfaces, the indexer on the list interfaces and, of these five, Add, Remove and Clear only on ICollection<T> and IList<T>.
Explain the two separate ladders, why an IList<T> variable fails CS1503 against an IReadOnlyList<T> parameter, and why the least-specialised parameter type serves every caller.
Show the judgment in review: catch read-only input typed as IList<T> or List<T>, and say plainly that a read-only interface limits the caller, not the owner.
Connect parameter typing to a library's surface: wide input types cost nothing to keep, while narrowing one later forces callers to change code.
## Two ladders over one base Every generic collection in .NET implements `IEnumerable<T>`, the interface that lets `foreach` walk it. On top of that base the base class library defines **two separate ladders** of interfaces, and each rung adds a capability: | Interface | Adds | Typical members | |---|---|---| | `IEnumerable<T>` | enumeration only | `GetEnumerator()` | | `IReadOnlyCollection<T>` | a known size | `Count` | | `IReadOnlyList<T>` | positional reads | `this[int]` with `get` only | | `ICollection<T>` | size and mutation | `Count`, `IsReadOnly`, `Add`, `Remove`, `Clear`, `Contains`, `CopyTo` | | `IList<T>` | positional mutation | `this[int]` with `get` and `set`, `IndexOf`, `Insert`, `RemoveAt` | The declarations in the runtime source are short: `IList<T> : ICollection<T>`, `ICollection<T> : IEnumerable<T>`, `IReadOnlyList<out T> : IReadOnlyCollection<T>` and `IReadOnlyCollection<out T> : IEnumerable<T>`. The dictionary pair follows the same split: `IReadOnlyDictionary<TKey,TValue>` offers `ContainsKey`, `TryGetValue`, a get-only indexer, `Keys` and `Values`, while `IDictionary<TKey,TValue>` adds `Add`, `Remove` and a settable indexer. ## The ladders do not meet `List<T>`, arrays, `Collection<T>` and `ReadOnlyCollection<T>` implement **both** `IList<T>` and `IReadOnlyList<T>`, so a variable of any of those concrete types converts to either interface. The interfaces themselves are unrelated, because `ICollection<T>` derives only from `IEnumerable<T>`. Code that holds an `IList<T>` therefore cannot hand it to a method that wants `IReadOnlyList<T>`: ```plaintext error CS1503: Argument 1: cannot convert from 'System.Collections.Generic.IList<string>' to 'System.Collections.Generic.IReadOnlyList<string>' ``` The object behind the reference may well be a `List<string>`, but the compiler only sees the static type. The caller has to pass the concrete variable, cast, or wrap. ## What "read-only" in the name promises The word describes **the view the caller gets**, not the collection: - **Through an `IReadOnlyList<T>` reference** you cannot call `Add`, `Remove` or set an element; the compiler simply finds no such members. - **The owner can still change it.** A `List<T>` passed as `IReadOnlyList<T>` keeps growing when its owner calls `Add`, and the next `Count` shows it. - **The caller may be able to cast back.** If the object is a `List<T>`, a cast recovers the mutable list; stopping that needs a wrapper or a copy. - **It is not immutability.** A collection that can never change is a different type family, covered in the material on immutable and frozen collections. ## Choosing a parameter type A parameter type is a demand on every caller, so ask for no more than the method uses. The .NET design guidelines put it as "use the least-specialized type possible as a parameter type", and note that most members taking collections use `IEnumerable<T>`. 1. **Only loops once:** `IEnumerable<T>`. Arrays, `List<T>`, `HashSet<T>`, dictionary key collections and query results all fit. 2. **Loops and needs the size up front** (to pre-size a buffer, to reject an empty input): `IReadOnlyCollection<T>`. 3. **Reads by index** (binary search, pairing neighbours, reading the first and last item): `IReadOnlyList<T>`. 4. **Is meant to change the caller's collection** (a `Fill` or `RemoveExpired` helper): `ICollection<T>` or `IList<T>`, and the method's name should say so. The guidelines also advise against taking `ICollection<T>` just to read `Count`: the mutable interface tells every reader that the method may add or remove items. `IReadOnlyCollection<T>` says the same thing about size without that implication. Two details make the choice concrete. First, `IEnumerable<T>` has no `Count` property; LINQ's `Count()` extension method reads `Count` when the object implements `ICollection<T>` and otherwise walks the whole sequence, so a method that genuinely needs the size should ask for it in the signature. Second, a mutable parameter type does not guarantee that mutation works: an array converts implicitly to `IList<T>`, and its `Add` then throws `NotSupportedException` at run time, because an array's length is fixed. ## Why this matters in review - A method typed `void Print(List<Student> students)` forces callers holding an array or a `HashSet<T>` to copy into a list first. - A method typed `IList<T>` for input it only reads invites the next maintainer to start mutating the caller's data. - A method typed `IReadOnlyList<T>` documents in the signature that it reads by position and leaves the collection alone, and the compiler enforces the second half. Return types follow the mirror-image rule, promising what the type can keep providing; that decision, and what changing it later costs a published library, is a question of its own.
- Why does LINQ's Count() enumerate a custom type that implements only IReadOnlyCollection<T>?`Enumerable.Count<TSource>()` in .NET 10 looks for `ICollection<T>`, LINQ's own internal iterator types and the non-generic `ICollection` before it falls back to walking the sequence; `IReadOnlyCollection<T>` is not on that list, and `TryGetNonEnumeratedCount` returns `false` for such a type. `ReadOnlyCollection<T>` implements `IList<T>` as well, which is one reason `Count()` on it reads `Count` directly.
- A method needs only Count and a foreach; why not declare the parameter as ICollection<T>?`ICollection<T>` carries `Add`, `Remove` and `Clear`, so the signature tells readers the method may change the caller's collection, and it excludes types that implement only the read-only interfaces. `IReadOnlyCollection<T>` gives `Count` and enumeration with no mutators, and `List<T>`, arrays and `HashSet<T>` all implement it.
- What does IReadOnlyDictionary<TKey,TValue> let a caller do?Look up with `TryGetValue`, `ContainsKey` or the get-only indexer, read `Count`, enumerate `KeyValuePair<TKey,TValue>` entries, and read `Keys` and `Values` as `IEnumerable<T>`. There is no `Add`, `Remove` or setter. `Dictionary<TKey,TValue>` implements it, so the same cast-back caveat applies as for lists.
- IReadOnlyList<T> guarantees the list's contents will never change.
- IList<T> inherits from IReadOnlyList<T>, so it converts implicitly.
- ICollection<T> is the read-only counterpart of IList<T>.
- Every parameter should be List<T> because callers usually have one.
- IEnumerable<T> has a Count property like the other interfaces.