Skip to main content

How to Return a Read-Only List with IReadOnlyList<T> in C#

· 9 min read
Jagdish Kumawat
Founder @ Dewiride

A method that returns IReadOnlyList<T> hands callers a list they can count and read by position, such as books.Count and books[0], but can't add to or remove from. The class that owns the list can still change it.

Microsoft's reference describes the interface in one line: Represents a read-only collection of elements that can be accessed by index. Its remarks say what read-only means here: The IReadOnlyList<T> represents a list in which the number and order of list elements is read-only.

It has the two things a caller needs to read a list: Count, which Gets the number of elements in the collection, and an indexer, which Gets the element at the specified index in the read-only list. It has no Add, Remove or Clear. That makes it a good return type for a class that keeps a List<T> private: callers read the list, and only the class changes it.

Syntax​

Syntax
public IReadOnlyList<T> <MethodName>() => <list>.AsReadOnly();

IReadOnlyList<T> <items> = <owner>.<MethodName>();
int <count> = <items>.Count;
T <item> = <items>[<index>];
PartWhat it is
IReadOnlyList<T>The return type: a list callers can count and read by position, but not change
TThe type of the items, such as string
<list>.AsReadOnly()Wraps the class's own List<T>, so callers get a read-only view of it
<items>.CountHow many items the list holds
<items>[<index>]The item at a position. The first item is at 0

The same type works for a parameter: a method that takes IReadOnlyList<T> accepts a List<T> or an array.

The Example​

A console app called ReadOnlyListReturn has a Bookshelf class that keeps its books in a private List<string> and returns them as an IReadOnlyList<string>. A PrintNumbered method takes an IReadOnlyList<string> too, and gets a List<string> once and an array once.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n ReadOnlyListReturn
cd ReadOnlyListReturn
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/ReadOnlyListReturn/ReadOnlyListReturn.csproj:
Determining projects to restore...
Restored /Users/you/source/ReadOnlyListReturn/ReadOnlyListReturn.csproj (in 45 ms).
Restore succeeded.

dotnet new console -n ReadOnlyListReturn creates a folder named ReadOnlyListReturn with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or ReadOnlyListReturn.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First fill a shelf and read its books:

Program.cs (read the books)
// A bookshelf keeps its books in a List<string> that only the shelf can change.
Bookshelf shelf = new();
shelf.Add("Dune");
shelf.Add("Emma");
shelf.Add("Beloved");

// GetBooks returns an IReadOnlyList<string>: you can count it and read any position.
IReadOnlyList<string> books = shelf.GetBooks();
Console.WriteLine($"Books on the shelf: {books.Count}");
Console.WriteLine($"First book: {books[0]}, last book: {books[books.Count - 1]}");

shelf.GetBooks() returns an IReadOnlyList<string>. books.Count is how many books it holds, books[0] is the first one and books[books.Count - 1] the last.

Then let the shelf add a book after books was read:

Program.cs (the shelf adds a book)
// The shelf can still add books, and the read-only list shows them.
shelf.Add("Ulysses");
Console.WriteLine($"After the shelf adds one more: {books.Count} books");

books is not touched here: only the shelf changes its own list.

Then a method with an IReadOnlyList<string> parameter:

Program.cs (a read-only list parameter)
// A parameter of type IReadOnlyList<string> takes a List<string> and an array alike.
List<string> borrowed = ["Matilda", "Persuasion"];
string[] wishList = ["Rebecca"];
PrintNumbered("Borrowed", borrowed);
PrintNumbered("Wish list", wishList);

static void PrintNumbered(string heading, IReadOnlyList<string> titles)
{
Console.WriteLine($"{heading}:");
for (int i = 0; i < titles.Count; i++)
{
Console.WriteLine($" {i + 1}. {titles[i]}");
}
}

borrowed is a List<string> and wishList is a string[]. Both are passed to PrintNumbered without a cast. Inside, titles.Count and titles[i] are all the method needs, and the parameter type means it can't add or remove anything.

Last, the class that owns the list:

Program.cs (the Bookshelf class)
class Bookshelf
{
private readonly List<string> _books = [];

public void Add(string title) => _books.Add(title);

// Callers get a read-only list: Count and an indexer, but no Add or Remove.
public IReadOnlyList<string> GetBooks() => _books.AsReadOnly();
}
  • private readonly List<string> _books: the real list. Only code inside Bookshelf can reach it.
  • Add: the one way to put a book on the shelf.
  • GetBooks() => _books.AsReadOnly(): returns the list through a read-only wrapper. The reference: Returns a read-only ReadOnlyCollection<T> wrapper for the current collection.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Books on the shelf: 3
First book: Dune, last book: Beloved
After the shelf adds one more: 4 books
Borrowed:
1. Matilda
2. Persuasion
Wish list:
1. Rebecca

macOS-style terminal window titled Terminal — ReadOnlyListReturn showing dotnet run printing Books on the shelf: 3, First book: Dune, last book: Beloved, After the shelf adds one more: 4 books, then Borrowed with Matilda and Persuasion numbered 1 and 2, and Wish list with Rebecca numbered 1

The shelf had 3 books, and books[0] and books[books.Count - 1] read Dune and Beloved. After the shelf added Ulysses, the same books variable reported 4 books, although nobody read it again. AsReadOnly doesn't copy the list, it wraps it. The reference: However, if changes are made to the underlying List<T> object, the read-only collection reflects those changes. PrintNumbered numbered the 2 books in the List<string> and the 1 book in the string[].

The Complete File​

macOS-style code window titled Program.cs — ReadOnlyListReturn showing a Bookshelf filled with Dune, Emma and Beloved, GetBooks read into an IReadOnlyList of string whose Count and first and last books are printed, the shelf adding Ulysses, a PrintNumbered method with an IReadOnlyList of string parameter called with a List and an array, and the Bookshelf class whose GetBooks returns its private list through AsReadOnly

Program.cs
// A bookshelf keeps its books in a List<string> that only the shelf can change.
Bookshelf shelf = new();
shelf.Add("Dune");
shelf.Add("Emma");
shelf.Add("Beloved");

// GetBooks returns an IReadOnlyList<string>: you can count it and read any position.
IReadOnlyList<string> books = shelf.GetBooks();
Console.WriteLine($"Books on the shelf: {books.Count}");
Console.WriteLine($"First book: {books[0]}, last book: {books[books.Count - 1]}");

// The shelf can still add books, and the read-only list shows them.
shelf.Add("Ulysses");
Console.WriteLine($"After the shelf adds one more: {books.Count} books");

// A parameter of type IReadOnlyList<string> takes a List<string> and an array alike.
List<string> borrowed = ["Matilda", "Persuasion"];
string[] wishList = ["Rebecca"];
PrintNumbered("Borrowed", borrowed);
PrintNumbered("Wish list", wishList);

static void PrintNumbered(string heading, IReadOnlyList<string> titles)
{
Console.WriteLine($"{heading}:");
for (int i = 0; i < titles.Count; i++)
{
Console.WriteLine($" {i + 1}. {titles[i]}");
}
}

class Bookshelf
{
private readonly List<string> _books = [];

public void Add(string title) => _books.Add(title);

// Callers get a read-only list: Count and an indexer, but no Add or Remove.
public IReadOnlyList<string> GetBooks() => _books.AsReadOnly();
}

Common Mistakes​

MistakeWhat happensDo this instead
Calling Add on the list a method returnedbooks.Add("Beloved") didn't build: error CS1061: 'IReadOnlyList<string>' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'IReadOnlyList<string>' could be found (are you missing a using directive or an assembly reference?)Add through the class that owns the list, as shelf.Add("Ulysses") does
Returning the List<T> itself, as in GetBooks() => _booksIt builds, but a caller cast the result back with (List<string>)books, added a book, and the shelf then held 2 books instead of 1Return _books.AsReadOnly(). The same cast then threw InvalidCastException: Unable to cast object of type 'System.Collections.ObjectModel.ReadOnlyCollection`1[System.String]' to type 'System.Collections.Generic.List`1[System.String]'. and the shelf kept its 1 book
Passing a LINQ query to an IReadOnlyList<T> parameterPrintNumbered(shortTitles), where shortTitles held what titles.Where(...) returned, didn't build: error CS1503: Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable<string>' to 'System.Collections.Generic.IReadOnlyList<string>'Turn the query into a list first: PrintNumbered(titles.Where(...).ToList()) printed 1. Dune and 2. Emma

FAQ​

Is the read-only list a copy?​

No. It's a view of the class's own list, which is why books went from 3 to 4 books in the run. When callers need a snapshot that doesn't change, return a copy. A check gave the shelf a GetBooksCopy() => [.. _books] method, which copies the books into a new collection: after the shelf added a fourth book, the copy still said Copy: 3 books and the wrapper said Read-only wrapper: 4 books.

Why not return an IEnumerable instead?​

An IEnumerable<T> can be looped over, but it has no Count property and no indexer. titles[0] on an IEnumerable<string> didn't build: error CS0021: Cannot apply indexing with [] to an expression of type 'IEnumerable<string>'. IReadOnlyList<T> gives callers both, and still no way to add or remove.

Can callers change the items inside the list?​

Yes, when the items are objects with settable properties. The reference: The content of list elements is not guaranteed to be read-only. A check returned an IReadOnlyList<Book> whose Book has a Title { get; set; }. A caller set books[0].Title, and the shelf then printed The shelf's first book: Changed by a caller. The list stops callers from adding and removing books, not from changing a book.

Conclusion​

Return IReadOnlyList<T> when callers need to count a list and read it by position, but must not add or remove items. Keep the List<T> private, return it through AsReadOnly() so a cast can't get around the wrapper, and remember that the wrapper shows the class's later changes. When callers need a snapshot instead, return a copy.

Additional Resources​