IEnumerable vs IList


IEnumerable and IList are both interfaces in .NET used to work with collections, but they serve different purposes and provide different functionalities. Here’s a comparison to help understand their differences:

IEnumerable

  • Purpose - Represents a sequence of elements that can be enumerated (iterated) one at a time. It is the base interface for all non-generic collections that support enumeration.
  • Methods - Defines a single method, GetEnumerator(), which returns an IEnumerator that can be used to iterate through the collection.
  • Functionality - Provides read-only access to the elements in a collection. It does not provide methods for modifying the collection (e.g., adding, removing elements).
  • Usage - Ideal for querying data and working with collections that should not be modified. Commonly used with LINQ queries.

Example

IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
foreach (var number in numbers)
{
    Console.WriteLine(number);
}

IList

  • Purpose - Represents a collection of elements that can be individually accessed by index and supports read-write operations. It is a more specific interface that extends IEnumerable to include methods for modifying the collection.
  • Methods - Includes methods and properties like Add(), Remove(), Insert(), IndexOf(), and Item[] (indexer), in addition to the enumeration methods from IEnumerable.
  • Functionality - Allows for both read and write operations on the collection. It provides indexed access to elements and supports various modifications.
  • Usage - Ideal when you need to both access elements by index and modify the collection. It is commonly used for collections that need to be altered:

Example

IList<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6);
numbers.Remove(2);
Console.WriteLine(numbers[0]); // Outputs: 1

Difference Between IEnumerable and IList

IEnumerable IList
Enumerates through a collection. Provides indexed access and modification.
GetEnumerator() Add(), Remove(), Insert(), IndexOf(), Item[]
Read-only, no modification. Read-write, supports modification and indexing.
Use for querying or iterating without modification. Use for collections where you need to modify or access elements by index.

Choosing Between IEnumerable and IList

  • Use IEnumerable if you only need to iterate over the collection and do not need to modify it.
  • Use IList if you need to add, remove, or modify elements, or if you need to access elements by their index.

Prev Next