Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

Sandeep picture Sandeep · Aug 31, 2010 · Viewed 100.4k times · Source

Is there any specific reason why indexing is not allowed in IEnumerable.

I found a workaround for the problem I had, but just curious to know why it does not allow indexing.

Thanks,

Answer

James Curran picture James Curran · Aug 31, 2010

Because it's not.

Indexing is covered by IList. IEnumerable means "I have some of the powers of IList, but not all of them."

Some collections (like a linked list), cannot be indexed in a practical way. But they can be accessed item-by-item. IEnumerable is intended for collections like that. Note that a collection can implement both IList & IEnumerable (and many others). You generally only find IEnumerable as a function parameter, meaning the function can accept any kind of collection, because all it needs is the simplest access mode.