IEnumerable vs ICollection
Uncategorized
Sthembiso Mashiyane  

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:

Notice: IEnumerable doesn’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 Count and IsReadOnly.
  • Provides methods such as Add(), Remove(), Contains(), and CopyTo().
  • Suitable when you need to know the number of elements or modify the collection.

Example:

Reference: Microsoft Docs – ICollection<T>


recap-diagram

IEnumerable vs ICollection

Key Differences

FeatureIEnumerable<T>ICollection<T>
PurposeIterate itemsIterate + modify + count
MethodsGetEnumerator()Add(), Remove(), Contains(), CopyTo()
PropertiesNoneCount, IsReadOnly
PerformanceLightweight, deferred executionSlightly 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 an IEnumerable<T> triggers enumeration over all elements, which can be costly. Using ICollection<T> avoids this because it provides a built-in Count property.
  • 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#.

Leave A Comment