Middle
How does List differ from IEnumerable?
sobes.tech AI
Answer from AI
IEnumerable is an interface that provides the ability to iterate over a collection using an enumerator (iterator). It defines only one method, GetEnumerator(), which returns an object for sequential traversal of elements.
List<T> is a concrete collection implementation that stores elements in an array with dynamic resizing. It implements many interfaces, including IEnumerable<T>, ICollection<T>, IList<T>.
Key differences:
IEnumerableonly provides read and iteration capabilities, does not guarantee index-based access, and does not support modification of the collection.List<T>allows adding, removing, modifying elements, and also provides fast index-based access.
Example:
IEnumerable<int> enumerable = new List<int> {1, 2, 3};
// Can iterate, but cannot add an element directly through IEnumerable
List<int> list = new List<int> {1, 2, 3};
list.Add(4); // Can modify the collection
int second = list[1]; // Index-based access