Advertisement
Advanced C#, Collections

How would you implement a custom, strongly-typed, read-only wrapper around a mutable collection to safely expose it from a class's public API?

Short answer

Wrap the internal mutable collection with ReadOnlyCollection (via .AsReadOnly()) or expose it typed as IReadOnlyList /IReadOnlyCollection — this prevents CONSUMERS from mutating your class's internal state directly through the exposed reference, while your class's own internal…

Save C# mock interview
Advertisement
AModel answer
Wrap the internal mutable collection with ReadOnlyCollection<T> (via .AsReadOnly()) or expose it typed as IReadOnlyList<T>/IReadOnlyCollection<T> — this prevents CONSUMERS from mutating your class's internal state directly through the exposed reference, while your class's own internal code retains full mutable access to the underlying List<T>.
public class Order {
  private readonly List<string> _items = new();
  public IReadOnlyList<string> Items => _items.AsReadOnly(); // consumers can read, but not mutate

  public void AddItem(string item) => _items.Add(item); // only the class itself can mutate
}
Real-world example
Safely exposing an entity's internal collection (like an Order's line items) without letting external code bypass validation by mutating it directly.
Likely follow-ups
  • Does wrapping with .AsReadOnly() create a deep copy, or does it still reflect live changes made through the class's own internal mutation methods?
Related topics