IEnumerable vs ICollection vs IList in C#: Key Differences and Usage
IEnumerable provides simple iteration over a collection. ICollection extends IEnumerable by adding size, add, and remove capabilities. IList further extends ICollection by supporting indexed access and insertion.Quick Comparison
Here is a quick table comparing IEnumerable, ICollection, and IList based on key features and usage.
| Feature | IEnumerable | ICollection | IList |
|---|---|---|---|
| Namespace | System.Collections | System.Collections | System.Collections |
| Supports iteration | Yes | Yes | Yes |
| Supports Count property | No | Yes | Yes |
| Supports Add/Remove methods | No | Yes | Yes |
| Supports indexed access | No | No | Yes |
| Supports insertion at index | No | No | Yes |
Key Differences
IEnumerable is the simplest interface that allows you to loop through a collection using foreach. It only guarantees that you can read items one by one, but it does not provide any information about the collection size or allow modification.
ICollection extends IEnumerable by adding the Count property and methods like Add, Remove, and Clear. This means you can check how many items are in the collection and modify it, but you cannot access items by position.
IList extends ICollection by adding indexed access through the this[int index] property. This lets you get or set items at specific positions and insert or remove items at any index, making it suitable for list-like collections.
Code Comparison
Using IEnumerable to iterate over a collection:
using System; using System.Collections; class Program { static void Main() { IEnumerable numbers = new int[] {1, 2, 3}; foreach (int num in numbers) { Console.Write(num + " "); } } }
IList Equivalent
Using IList to access and modify a collection by index:
using System; using System.Collections.Generic; class Program { static void Main() { IList<int> numbers = new List<int> {1, 2, 3}; numbers[1] = 20; // Modify element at index 1 numbers.Insert(2, 30); // Insert 30 at index 2 foreach (int num in numbers) { Console.Write(num + " "); } } }
When to Use Which
Choose IEnumerable when you only need to read or loop through a collection without modifying it or knowing its size. It is the most basic and flexible interface for iteration.
Choose ICollection when you need to know the number of items or add and remove elements but do not require indexed access.
Choose IList when you need full list functionality, including accessing, inserting, or removing items by their position in the collection.
Key Takeaways
IEnumerable is for simple read-only iteration.ICollection adds size and modification capabilities.IList supports indexed access and insertion.