0

I want to know the exact place where we should use IEnumberable<T>

I know how IEnumerable<T> work and returns IEnumerator<T> and all that but the ultimate goal of IEnumerable<T> is to query the data from the collection isn't it? That is what we can already do using foreach() loop ? So when to use IEnumerable<T>? what is the actual practical scenario where the IEnumerable<T> is the only option to query the collection?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
  • I'm not sure I understand what you're trying to ask. A `foreach` loop can loop over anything which implements `IEnumerable`. – canton7 Feb 13 '23 at 09:25
  • The point of `IEnumberale` isn't to "query a collection". The point is to represent any collection which can be iterated over. So anything which can be iterated over should implement `IEnumerable`, and that way you can use a `foreach` loop to loop over it – canton7 Feb 13 '23 at 09:26
  • I'm not sure what misunderstanding you have here, but unless you only iterate over arrays, `foreach` ***needs*** the type you are iterating over to implement `IEnumerable` to work. – Sweeper Feb 13 '23 at 09:26
  • I can loop on a collection using foreach() directly - so when to use IEnumerable? – Hammad Maqbool Feb 13 '23 at 09:27
  • 3
    @HammadMaqbool You can only iterate over the collection *because* it implements `IEnumerable` – canton7 Feb 13 '23 at 09:27
  • @canton7 /s/collection/sequence – Marc Gravell Feb 13 '23 at 09:28
  • 2
    @MarcGravell Yeah, and I've said a bunch of other things which aren't strictly true as well. Trying to be clear rather than completely correct, since the problem here is a conceptual misunderstanding rather than a problem with the details – canton7 Feb 13 '23 at 09:28
  • @HammadMaqbool when you use foreach, you use IEnumerable. Like others above said, the foreach keyword makes use of IEnumerable. – Orion Feb 13 '23 at 09:33

1 Answers1

6

but the ultimate goal of IEnumerable<T> is to query the data from the collection isn't it?

No; the goal of IEnumerable<T> is to provide access to a sequence, which may or may not be a collection. The point being to abstract away what the underlying source is. It could be a raw collection, but it could be:

  • some LINQ (or similar) projection (collection.Where(...).Select(...) etc)
  • an open query to ADO.NET, redis, a socket, gRPC, a file or some other data provider that isn't readily countable, repeatable, etc - just: "a sequence"
  • an in-process data generator
  • some producer/consumer setup
  • etc

If you know you're always iterating a collection, then sure: feel free to use the concrete type, or ICollection<T>/IList<T> etc; but: not every sequence is a collection.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900