skip to content

Your team publishes a C# library that other teams compile against; which collection types should its public members accept and return, and what does changing one later break?

level: principalimportance: should knowfreq 32%

answer

  1. accept little, promise carefully
  2. List<T> stays internal
  3. a hook-friendly base class
  4. the signature in compiled callers
  5. two overloads, one ambiguity

basics

~20 s

Accept the least a member uses, usually IEnumerable<T> or a read-only interface; return what you can keep promising, such as IReadOnlyList<T> or ReadOnlyCollection<T>, never List<T>. Changing a published type later breaks already-compiled callers with MissingMethodException.

solid answer

~40 s

For inputs, a published member takes the least it needs (`IEnumerable<T>`, `IReadOnlyCollection<T>` or `IReadOnlyList<T>`) so any caller's collection fits. For outputs, it returns what the library can promise for years: a read-only interface such as `IReadOnlyList<T>` keeps the implementation swappable, while a concrete `ReadOnlyCollection<T>` or `Collection<T>` subclass lets you add members later and, for read-write collections, intercept changes through `InsertItem` and `SetItem`. `List<T>` stays out of signatures, which CA1002 flags, and collection properties have no setter (CA2227). The choice is hard to undo: a method's return and parameter types are part of the reference compiled into every caller, so switching `List<Student>` to `IReadOnlyList<Student>` makes old binaries throw `MissingMethodException`, and recompiled callers that used `Add` stop compiling. Decide the types before the first release and treat a change as a major version.

code

csharp · 24 lines
csharp
using System.Collections.ObjectModel;

var course = new Course();
course.Students.Add(new Student("Ana"));
try { course.Students.Add(new Student(" ")); }
catch (ArgumentException e) { Console.WriteLine($"{e.GetType().Name}: {e.ParamName}"); }
Console.WriteLine(course.Students.Count);

public record Student(string Name);

// Collection<T> routes every Add, Insert and indexer set through InsertItem/SetItem
public class StudentCollection : Collection<Student>
{
    protected override void InsertItem(int index, Student item)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(item.Name, nameof(item));
        base.InsertItem(index, item);
    }
}

public class Course
{
    public StudentCollection Students { get; } = new();   // get-only: satisfies CA2227
}

go deeper

for a junior

Know the basic rule: public members should not take or return List<T>; they use interfaces such as IEnumerable<T> and IReadOnlyList<T>.

for a middle

Explain why inputs should be as general as possible, why a List<T> return leaks state, and what CA1002 and CA2227 flag.

for a senior

Show the mechanics of a break: return and parameter types are part of the compiled call, so a type change throws MissingMethodException in old binaries and breaks recompiled callers.

for a principal

Own the trade-off: interfaces keep the implementation swappable, concrete Collection<T> or ReadOnlyCollection<T> subclasses allow new members and hooks, and the choice is permanent once shipped.

## Why a library's choice is different Inside one application a collection type in a signature can be changed with a refactoring and a rebuild. A **published library** is compiled into other teams' assemblies, and those assemblies keep calling the exact member they were built against. Whatever collection type the first release exposes becomes a long-term promise, so the decision belongs to whoever owns the library's compatibility policy. ## Inputs: ask for little A parameter type is a demand on every caller. The .NET design guidelines say to "use the least-specialized type possible as a parameter type". - **`IEnumerable<T>`** suits anything that loops once and accepts every sequence. - **`IReadOnlyCollection<T>` or `IReadOnlyList<T>`** suit members that need `Count` or indexing; arrays, `List<T>` and `Collection<T>` all satisfy them. - **A caveat:** a caller holding an `IList<T>` variable cannot pass it to an `IReadOnlyList<T>` parameter (CS1503), because the two interfaces are unrelated. Adding a second overload that takes `IList<T>` does not fix it: a `List<T>` argument then matches both and the call fails with CS0121 ("The call is ambiguous..."). Pick one; `IEnumerable<T>` plus an internal type check is the usual escape. Widening a parameter later (say `List<T>` to `IEnumerable<T>`) is source-compatible for nearly every caller, but it is still a different method signature to callers that were already compiled. ## Outputs: promise what you can keep | Return type | What callers can rely on | What the library can still change | |---|---|---| | `List<T>` | every `List<T>` member, including `Add`, `Sort`, `Capacity` | almost nothing; callers may mutate your state | | `IReadOnlyList<T>` | `Count`, indexer, enumeration | the implementation behind it (a wrapper, an array, a custom type) | | `ReadOnlyCollection<T>` or a subclass | the same reads, plus `Contains`, `IndexOf`, `CopyTo` and any members a subclass adds | new helper members on the subclass | | `Collection<T>` subclass | full read-write access | validation and notifications via protected virtual hooks | The design-guidelines page, an older text that predates the read-only interfaces and does not mention them, recommends `ReadOnlyCollection<T>` (or a subclass) for read-only results, `Collection<T>` (or a subclass) for read-write ones, and "in rare cases" `IEnumerable<T>`. It also says to return an empty collection rather than `null`. `Collection<T>` routes `Add`, `Insert`, the indexer setter, `Remove` and `Clear` through `protected virtual` `InsertItem`, `SetItem`, `RemoveItem` and `ClearItems`, so a `StudentCollection : Collection<Student>` can reject a blank name on every path into the collection. `List<T>` has no virtual members to override, which is the reason **CA1002** ("Do not expose generic lists") exists. **CA2227** ("Collection properties should be read only") flags a settable collection property. Neither rule is enabled by default in .NET 10, so a team that wants them turns them on in `.editorconfig`. ## What changing a type later breaks In compiled IL, a call records the method's name, its parameter types **and its return type**. Change any of them and the old member no longer exists: 1. **Binary break.** A consumer compiled against `public List<string> GetStudents()` and run against a library where it now returns `IReadOnlyList<string>` fails at the call with `System.MissingMethodException: Method not found: 'System.Collections.Generic.List`1<System.String> Enrolment.Course.GetStudents()'`, even though its source would still compile. 2. **Source break.** When the consumer rebuilds, every use of `Add`, `Sort` or `AddRange` on the result stops compiling, and every `List<string> x = course.GetStudents();` needs a change. 3. **Behavioural break.** Moving from returning the live list to returning a copy (or the reverse) compiles everywhere and changes what callers observe. So the only cheap moment to pick a collection type is before the first release. Going wider later (returning `List<T>` where `IReadOnlyList<T>` was) is still a binary break, so even "generous" changes need a major version. ## A team rule that holds up - Parameters: `IEnumerable<T>` by default; a read-only interface when `Count` or indexing is genuinely used. - Returns: `IReadOnlyList<T>` or `IReadOnlyDictionary<TKey,TValue>` for read-only results when the implementation may change; a `ReadOnlyCollection<T>` or `Collection<T>` subclass when the type will grow helper members or needs change hooks. - No `List<T>`, `Dictionary<TKey,TValue>` or arrays in public signatures except in low-level, performance-tuned APIs, where the guidelines accept arrays. - Enable CA1002 and CA2227, and run a public-API diff in review so a collection type never changes by accident. The trade-off a lead owns is flexibility for the library against convenience for its callers: interfaces preserve the right to change internals, concrete types preserve the right to add members, and either way the decision is effectively permanent once shipped.

  • Why not publish both M(IList<T>) and M(IReadOnlyList<T>) so every caller's variable fits?
    `List<T>`, arrays and `Collection<T>` implement both interfaces, so passing one of them matches both overloads equally well and the compiler reports CS0121, an ambiguous call. Callers then need casts to pick an overload. A single `IEnumerable<T>` parameter, with an internal check for `IReadOnlyList<T>` or `IList<T>` to take a fast path, avoids the ambiguity.
  • When is IEnumerable<T> the right published return type?
    When the library will only ever promise forward iteration and wants the freedom to stream, compute or change storage. Callers then get no `Count` or indexer without materialising it themselves. Whether such a result should be lazy or materialised is a separate decision, covered with LINQ's deferred execution.
  • Is switching a return type from List<T> to IReadOnlyList<T> safe if every consumer rebuilds?
    Only for consumers that used read members. Code that called `Add`, `Sort` or `AddRange` on the result, or stored it in a `List<T>` variable, stops compiling; `var` locals adapt silently. Any consumer that is not rebuilt fails at run time with `MissingMethodException`. Either way it is a major-version change.

  • Returning List<T> is generous, since callers get the most functionality.
  • Changing List<T> to IReadOnlyList<T> is safe because List<T> implements it.
  • An IReadOnlyList<T> parameter accepts any list, IList<T> variables included.
  • Adding IList<T> and IReadOnlyList<T> overloads lets every caller pass anything.
  • A settable collection property is fine because callers can replace it.