Expose a Read-Only Collection in C# with AsReadOnly

A class that keeps a private List<T> often needs to let callers see the items without letting them add, remove or clear anything. List<T>.AsReadOnly() does that: it returns a ReadOnlyCollection<T> that wraps the list and rejects every attempt to modify it.

The pattern

using System.Collections.ObjectModel;

var order = new Order();
order.AddLine("2 x coffee");
Console.WriteLine(order.Lines.Count);   // 1

order.AddLine("1 x bagel");
Console.WriteLine(order.Lines.Count);   // 2

public class Order
{
    private readonly List<string> _lines = [];

    public Order()
    {
        Lines = _lines.AsReadOnly();
    }

    public IReadOnlyList<string> Lines { get; }

    public void AddLine(string line)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(line);
        _lines.Add(line);
    }
}

Callers can loop over order.Lines, read Count and index into it. The only way to change the list is through AddLine, so the class can validate input and keep its own rules.

Two details in this version are deliberate. The wrapper is created once in the constructor and reused, because every call to AsReadOnly() allocates a new wrapper object. And the property type is IReadOnlyList<T>, so callers do not even see Add or Remove methods. You can declare it as ReadOnlyCollection<T> instead if you prefer the concrete type.

It is a view, not a copy

The wrapper holds a reference to the original list. That is why Lines.Count went from 1 to 2 in the example above without asking for the property again: changes the owner makes show up immediately.

Usually that is what you want. It does mean the wrapper is not a snapshot. If another thread modifies the list while a caller enumerates the wrapper, the caller gets the same InvalidOperationException it would get from the list itself. When callers need a stable copy, return one: _lines.ToArray(), or an ImmutableList<T> from System.Collections.Immutable.

Why not just return IEnumerable<T>?

The original version of this post offered a second option: expose the list through a property typed as IEnumerable<T>.

public IEnumerable<string> Lines => _lines;

It looks read-only, but the object behind the property is still the real List<string>, and any caller can cast it back:

var list = (List<string>)order.Lines;
list.Clear();   // works, and bypasses AddLine entirely

The same is true when you return the list as IReadOnlyList<T> directly, without AsReadOnly(). The interface only hides methods from IntelliSense; it does not protect anything. With a ReadOnlyCollection<T>, the cast to List<string> throws InvalidCastException, and casting to IList<string> and calling Add throws NotSupportedException.

Whether that matters depends on who your callers are. Inside one codebase, returning IReadOnlyList<T> directly is a reasonable and allocation-free signal of intent. In a library that other teams use, wrap it.

Dictionaries and other collections

The same idea works for dictionaries. ReadOnlyDictionary<TKey, TValue> lives in System.Collections.ObjectModel, and since .NET 7 there is an AsReadOnly() extension method for IDictionary<TKey, TValue> as well:

private readonly Dictionary<string, decimal> _prices = new();

public IReadOnlyDictionary<string, decimal> Prices => _prices.AsReadOnly();

Like List<T>.AsReadOnly(), this allocates a new wrapper on every call, so store it in a field if the property is read in a hot path.

For lookup data that is built once and never changes, consider FrozenDictionary<TKey, TValue> or FrozenSet<T> (.NET 8, System.Collections.Frozen). They are truly immutable and faster to read than a regular dictionary.

The items themselves are not protected

A read-only collection stops callers from changing which items are in it. It does nothing to stop them changing the items. If Lines held OrderLine objects with settable properties, a caller could still write order.Lines[0].Quantity = 0. Make the item type immutable, for example a record with init properties, if that matters.

Related examples

Leave a Comment