I am struggling to understand the benefit of IEnumerable. I understand that Enumerables allow execution to be deferred to later on.
Please see the example here: https://msdn.microsoft.com/en-us/library/system.collections.ienumerable(v=vs.110).aspx. In this example, the array is already populated in the main class and then injected into an IEnumerable class. Therefore this appears to eliminate the advantage of deferring the execution until later on. What am I missing here?
The documentation you reference is merely a how could you implement it, rather than the most efficient way. Of course, the implementation shown has no use at all, since as you say the array is already constructed and enumerable on itself.
The sample is useful at best to show how a custom type can act like a collection, by implementing
IEnumerable
. This very generic interface can of course be used to be called from a variety of places where you don't need specific knowledge about the collection type, but that isn't shown in the sample.An enumerator is used to iterate over a set of data from begin to end. You can't read the previous item back since it can already be discarded (for example an iterator that needs to download very large files from a remote location, you might not want to cache them).