C# & CLR Internals (50 Qs)•Part 2: Concurrency, Zero-Allocation & Advanced Language Features (11 - 24)
What is the difference between IEnumerable<T>, ICollection<T>, IList<T>, and IReadOnlyList<T>?
senior LevelCode ExampleTypeScript
In Simple Words:
IEnumerable<T>: Read-only forward-only iteration. ExposesGetEnumerator(). Deferred execution; does not guarantee a known count or indexed access.ICollection<T>: InheritsIEnumerable<T>. Adds modification capabilities (Add,Remove,Clear) and an eagerCountproperty.IList<T>: InheritsICollection<T>. Adds indexer access (list[index]) and ordered position mutations (Insert,RemoveAt).IReadOnlyList<T>: ExposesCountand indexed read access (this[int index]), communicating immutability to API consumers.
csharp
// Best practice: Accept the least specific interface, return the most specific:
public void ProcessItems(IEnumerable<Order> orders) { /* Deferred iteration */ }
public IReadOnlyList<Order> GetActiveOrders() => _orders.AsReadOnly();