skip to content

In C#, an int[] seen as ICollection<int> reports IsReadOnly true, yet IList<int>'s indexer still writes to it; what do IsReadOnly and NotSupportedException tell a caller?

level: middleimportance: should knowfreq 30%

answer

  1. an interface you may not use
  2. fixed size is not read-only
  3. the indexer setter still works
  4. IsFixedSize on non-generic IList
  5. the wrapper refuses every write

basics

~10 s

ICollection<T>.IsReadOnly is the run-time hint that Add, Remove and Clear will throw NotSupportedException. An array reports true because its size is fixed, yet IList<T>'s indexer setter still replaces elements; ReadOnlyCollection<T> rejects every write.

solid answer

~40 s

Implementing `ICollection<T>` or `IList<T>` does not guarantee that every member works: an implementation may refuse a member by throwing `NotSupportedException`, and `ICollection<T>.IsReadOnly` is how a caller asks first. Arrays show how coarse that flag is. Through the generic interfaces an `int[]` reports `IsReadOnly` as `true`, and `Add`, `Insert`, `Remove` and `RemoveAt` throw `NotSupportedException` ("Collection was of a fixed size."), yet `IList<int>`'s indexer setter replaces elements. The non-generic `IList` is more precise for the same array: `IsReadOnly` is `false` and `IsFixedSize` is `true`. `ReadOnlyCollection<T>`, by contrast, reports `true` and throws from every mutator, the indexer setter included. So when code accepts a mutable interface it may receive an array or a wrapper, and the safer design is a parameter type whose members the method can always use.

code

csharp · 17 lines
csharp
int[] seats = { 101, 102 };
ICollection<int> asCollection = seats;
IList<int> asList = seats;

Console.WriteLine(asCollection.IsReadOnly);   // True
asList[0] = 999;                              // allowed: replaces an element
Console.WriteLine(seats[0]);                  // 999

try { asCollection.Add(103); }
catch (NotSupportedException e) { Console.WriteLine(e.Message); }

var nonGeneric = (System.Collections.IList)seats;
Console.WriteLine($"{nonGeneric.IsReadOnly} {nonGeneric.IsFixedSize}"); // False True

IList<int> wrapped = Array.AsReadOnly(seats);
try { wrapped[0] = 1; }
catch (NotSupportedException e) { Console.WriteLine(e.Message); }

go deeper

for a junior

Remember that an array has a fixed length, so Add or Remove through IList<T> throws NotSupportedException even though it compiles.

for a middle

Explain IsReadOnly as the run-time check for unsupported mutators, why arrays report true yet accept indexer writes, and what IsFixedSize adds on the non-generic IList.

for a senior

Diagnose a NotSupportedException from Add as an array or wrapper reaching code that assumed List<T>, and fix it by narrowing the parameter type rather than catching.

for a principal

Prefer signatures that make unsupported operations unrepresentable, the read-only interfaces for input, over runtime IsReadOnly checks scattered through a codebase.

## Interfaces with members you may not call The mutable collection interfaces predate the read-only ones, and the base class library uses them for types that can only partly honour them. The convention is that an implementation which cannot perform an operation throws **`NotSupportedException`**, and `ICollection<T>` carries a property, **`IsReadOnly`**, that lets a caller check before trying. That makes `ICollection<T>` and `IList<T>` a promise about the **shape** of the API, not a guarantee that `Add` will succeed. ## Arrays through the generic interfaces A single-dimensional array such as `int[]` implements `IList<int>`, `ICollection<int>`, `IReadOnlyList<int>` and `IReadOnlyCollection<int>`. On CoreCLR the generic interface calls are served by a runtime helper (`SZArrayHelper` in the runtime source), and it behaves like this: | Member reached through the interface | Result on an `int[]` | |---|---| | `ICollection<int>.IsReadOnly` | `true` | | `Add`, `Remove` | `NotSupportedException`: "Collection was of a fixed size." | | `IList<int>.Insert`, `RemoveAt` | `NotSupportedException`, same message | | `Clear` | `NotSupportedException` | | `IList<int>` indexer `get` and `set` | both work; `set` writes into the array | | `Contains`, `IndexOf`, `CopyTo` | work | The surprise is the pair in the middle: the array says it is read-only, and yet a write through the indexer goes straight into the array. The generic flag folds two different limits, **fixed size** and **no writes at all**, into one `bool`. ## The non-generic interface is more precise The older `System.Collections.IList` has two flags. For the same array, `IList.IsReadOnly` is `false` and `IList.IsFixedSize` is `true`, which is exactly right: elements can change, the length cannot. Code that needs to tell "can replace" from "can grow" can only learn it from the non-generic interface or from the concrete type. ## ReadOnlyCollection<T> refuses everything `ReadOnlyCollection<T>` (and `Array.AsReadOnly(array)`, which returns one) implements `IList<T>` explicitly so that it can be passed to older APIs, and: - reports `ICollection<T>.IsReadOnly` as `true`; - throws `NotSupportedException` ("Collection is read-only.") from `Add`, `Insert`, `Remove`, `RemoveAt`, `Clear` **and** the indexer setter; - forwards `Count`, the indexer getter, `Contains`, `IndexOf` and `CopyTo` to the wrapped list. So `Array.AsReadOnly(seats)` is the way to hand out an array that callers can read through `IList<T>` but cannot write through, which passing the array as `IReadOnlyList<T>` does not achieve (a cast back to `int[]` recovers it). ## What a caller should do with this 1. **When receiving `ICollection<T>` to fill**, check `IsReadOnly` and fail early with an `ArgumentException` naming the parameter, rather than letting `NotSupportedException` escape from deep inside a loop half-way through. 2. **When only reading**, do not accept `ICollection<T>` or `IList<T>` at all; accept `IReadOnlyList<T>` or `IEnumerable<T>`, and the question never arises. 3. **When implementing a custom read-only collection** that must also implement `ICollection<T>` (for older APIs, or so LINQ's `Count()` reads `Count` directly), return `true` from `IsReadOnly` and throw `NotSupportedException` from every mutator, as the .NET design guidelines ask. 4. **When a NotSupportedException appears in a log** from `Add` on an `IList<T>`, look for an array or a read-only wrapper flowing into code that assumed a `List<T>`. ## How other BCL types answer - **`List<T>`** reports `IsReadOnly` as `false` and supports every member. - **`ReadOnlyCollection<T>`** reports `true` and refuses every mutator. - **`Collection<T>`** forwards `IsReadOnly` from the list it wraps, so a `Collection<T>` built over an array reports `true` and throws on `Add`. The pattern is consistent: the flag describes whether the collection's size and membership can change, and the member that throws tells you which operation was refused. ## Why this still matters Arrays flow into `IList<T>` parameters all the time, because the conversion is implicit and compiles without a cast. A helper written and tested against `List<T>` arguments works until someone passes `new[] { ... }` or a collection expression targeting an array, and then the first `Add` throws at run time. The compiler cannot help, because the interface really does declare `Add`; only a narrower parameter type moves the failure to compile time.

  • What does Array.AsReadOnly(seats) give you that passing seats as IReadOnlyList<int> does not?
    An `int[]` passed as `IReadOnlyList<int>` is still the array, so a caller can cast it back to `int[]`, or to `IList<int>`, and overwrite elements. `Array.AsReadOnly` returns a `ReadOnlyCollection<int>` wrapper: a cast to `int[]` fails with `InvalidCastException`, and its `IList<int>` indexer setter throws `NotSupportedException`. The wrapper is still a live view of the array.
  • Why does ReadOnlyCollection<T> implement IList<T> at all, if every mutator throws?
    So it can be passed to APIs written against `IList<T>` or the non-generic `IList`, and so code that checks for `ICollection<T>`, such as LINQ's `Count()`, reads `Count` directly instead of enumerating. The mutators are implemented explicitly, so they are invisible on a `ReadOnlyCollection<T>` variable and appear only through the interface.

  • If a type implements ICollection<T>, its Add method is guaranteed to work.
  • IsReadOnly true means no element can be changed through any interface.
  • Calling Add on an array through IList<T> grows it like a List<T>.
  • An array passed as IReadOnlyList<T> cannot be written to by the callee.
  • Add on an array through ICollection<T> fails to compile with CS1061.