- Published on
What is IReadOnlyCollection<T> in .NET?
- Authors
- Name
- Jeevan Wijerathna
- @iamjeevanvj
β
What is IReadOnlyCollection<T>
in .NET?
IReadOnlyCollection<T>
IReadOnlyCollection<T>
T
It is defined in the
System.Collections.Generic
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 property.
Count
π When to Use IReadOnlyCollection<T>
IReadOnlyCollection<T>
Use
IReadOnlyCollection<T>
-
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 only guarantees enumeration.
IEnumerable<T>
- Using adds the
IReadOnlyCollection<T>
guarantee and communicates the intent that no mutation should happen.Count
- Using
-
Better than returning
orList<T>
directly:T[]
- It avoids exposing unnecessary methods like ,
Add
, etc.Remove
- 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
- See the items.
- Count the items.
- But not modify the list (,
Add
, etc.).Remove
π Comparison to Other Interfaces
| Interface | Can Modify? | Has Count? | Enumerator? | Intent | | ------------------------ | ----------- | ---------- | ----------- | --------------------------- | |
IEnumerable<T>
IReadOnlyCollection<T>
ICollection<T>
List<T>
T[]
π§ Tip
- is especially useful in public APIs, DDD entities/aggregates, and library development, where encapsulation and immutability matter.
IReadOnlyCollection<T>
- Internally, you can still use a or
List<T>
and expose it asHashSet<T>
.IReadOnlyCollection<T>