Understanding IEnumerable vs ICollection in C#
When working with collections in C#, two interfaces are foundational: IEnumerable<T> and ICollection<T>. Knowing the difference between them is crucial for writing efficient, maintainable, and correct code.
What is IEnumerable<T>?
IEnumerable<T> is the most basic interface for collections in .NET. It allows forward-only iteration over a sequence of items.
Key points:
- Defined in
System.Collections.Generic. - Provides the
GetEnumerator()method to iterate items. - Supports deferred execution in LINQ queries, meaning the sequence is only evaluated when enumerated.
- Ideal for read-only access or streaming large datasets.
Example:
IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
foreach (var number in numbers)
{
Console.WriteLine(number);
}
Notice:
IEnumerabledoesn’t provide a way to add, remove, or count elements efficiently.
Reference: Microsoft Docs – IEnumerable<T>
What is ICollection<T>?
ICollection<T> extends IEnumerable<T> and adds features for collection management.
Key points:
- Also defined in
System.Collections.Generic. - Includes properties like
CountandIsReadOnly. - Provides methods such as
Add(),Remove(),Contains(), andCopyTo(). - Suitable when you need to know the number of elements or modify the collection.
Example:
ICollection<string> names = new List<string> { "Alice", "Bob", "Charlie" };
names.Add("David");
Console.WriteLine($"Total names: {names.Count}");
Reference: Microsoft Docs – ICollection<T>
IEnumerable vs ICollection
Key Differences
| Feature | IEnumerable<T> | ICollection<T> |
|---|---|---|
| Purpose | Iterate items | Iterate + modify + count |
| Methods | GetEnumerator() | Add(), Remove(), Contains(), CopyTo() |
| Properties | None | Count, IsReadOnly |
| Performance | Lightweight, deferred execution | Slightly heavier, supports modification |
When to Use Each
- Use
IEnumerable<T>:- When you only need to read or iterate items.
- When working with LINQ queries for deferred execution.
- When dealing with large datasets to reduce memory usage.
- Use
ICollection<T>:- When you need to count items frequently.
- When you want to add, remove, or modify elements.
- When a fixed-size or modifiable collection is required.
Performance Considerations
- Calling
.Count()on anIEnumerable<T>triggers enumeration over all elements, which can be costly. UsingICollection<T>avoids this because it provides a built-inCountproperty. - Multiple iterations over an
IEnumerable<T>may result in repeated computations if the sequence is generated on-the-fly. Consider converting to a list with.ToList()if multiple enumerations are needed.
Reference: Microsoft Docs – Collections Overview
Conclusion
IEnumerable<T> and ICollection<T> serve different purposes:
IEnumerable<T>is perfect for iteration and streaming.ICollection<T>is suitable for counting and modification.
Understanding these differences helps you write more efficient, readable, and maintainable code in C#.