When to use IEnumerable vs IList vs ICollection?

In C#, IEnumerable, IList, and ICollection are interfaces that represent different types of collections. Here’s a brief characterization of each:

What is IEnumerable and how to use it?

  • IEnumerable defines an iterator that allows you to iterate over the elements in a collection.
  • It is the most general interface among the three and includes only the GetEnumerator method, which returns an object implementing the IEnumerator interface.
  • IEnumerable only supports forward-only iteration of the collection.
IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
foreach (var number in numbers)
{
    //Iterate throught list
}

What is IList and how to use it?

IList inherits from ICollection and IEnumerable and adds indexed access to elements.
It provides methods for adding, removing, indexing, and other operations, making it more feature-rich than IEnumerable.

IList names = new List { "Anna", "Bob", "Charlie" };
string firstPerson = names[0]; // Accessing an element using an index

 

What is ICollection and how to use it?

ICollection inherits from IEnumerable and defines operations for managing collection elements, such as adding, removing, and checking if an element exists. ICollection does not include direct indexing operations.

ICollection prices = new List { 19.99, 29.99, 39.99 };
prices.Add(49.99); // Adding a new element
bool containsPrice = prices.Contains(29.99); // Checking if an element exists

Summary

In summary, use IEnumerable when you only need to iterate over the collection, IList when you require indexed access and additional list-specific operations, and ICollection when you need to manage elements in the collection but don’t necessarily need direct indexing. The choice depends on the specific requirements of your code.

Buy Me A Coffee

Leave a Comment