- Published on
What is IReadOnlyCollection<T> in .NET?
- Authors

- Name
- Jeevan Wijerathna
- @iamjeevanvj
β
What is IReadOnlyCollection<T> in .NET?
IReadOnlyCollection<T> is an interface in the .NET Framework that represents a read-only, enumerable collection of elements of type T.
It is defined in the System.Collections.Generic namespace and looks like this:
public interface IReadOnlyCollection<out T> : IEnumerable<T>{ int Count { get; }}So it's essentially:
- A read-only collection (you can't add/remove/modify items).
- You can enumerate it using
foreach. - You can get the number of elements via the
Countproperty.
π When to Use IReadOnlyCollection<T>
Use IReadOnlyCollection<T> when:
-
You want to expose a collection as read-only:
- Consumers of your code can read the elements but can't modify them.
- It enforces immutability at the API boundary.
-
You want to convey intent clearly:
- Using
IEnumerable<T>only guarantees enumeration. - Using
IReadOnlyCollection<T>adds theCountguarantee and communicates the intent that no mutation should happen.
- Using
-
Better than returning
List<T>orT[]directly:- It avoids exposing unnecessary methods like
Add,Remove, etc. - Hides the underlying data structure.
- It avoids exposing unnecessary methods like
β Example
public class Order{ private readonly List<string> _items = new List<string>();
public void AddItem(string item) { _items.Add(item); }
public IReadOnlyCollection<string> Items => _items;}This ensures that callers of Order.Items can:
- See the items.
- Count the items.
- But not modify the list (
Add,Remove, etc.).
π Comparison to Other Interfaces
| Interface | Can Modify? | Has Count? | Enumerator? | Intent |
|---|---|---|---|---|
IEnumerable<T> | β | β | β | Enumeration only |
IReadOnlyCollection<T> | β | β | β | Read-only access with count |
ICollection<T> | β | β | β | Modifiable collection |
List<T> / T[] | β | β | β | Concrete mutable collection |
π§ Tip
IReadOnlyCollection<T>is especially useful in public APIs, DDD entities/aggregates, and library development, where encapsulation and immutability matter.- Internally, you can still use a
List<T>orHashSet<T>and expose it asIReadOnlyCollection<T>.