I’m in the process of learning Interfaces. I’ve been reading through some books/articles and so far so good – I’ve written a few sample Interfaces of my own. Yay 🙂
Now, I’ve noticed that one of the most popular C# Interfaces around is the IEnumerable Interface. It’s used quite a lot for all sorts of collections etc..
Anyway, I’d like to examine it, with intent to further understand how it actually works. I’ve searched Google but I can’t seem to find a reference to the actual source code, but I imagine it would contain the Interface itself, and a class(es) containing the various Methods.
So, is anyone able to help?
Much appreciated
IEnumerable is pretty simple:
And for completeness, IEnumerator
But more often what you’re really seeing in code samples is IEnumerable<T>
And again for completeness, IEnumerator<T> (with IDisposable):
That’s really all there is to it. There is no direct implementation code for any of this that’s specific to IEnumerable or the related code show here. Rather, types like arrays or List<T> will inherit from IEnumerable and implement the required methods. Everything else beyond that is done via extension methods.
What makes it all even more powerful are these items:
foreachkeyword supports looping over anything that has aGetEnumerator()method that returns an IEnumerator, and therefore you can use any type that implements IEnumerable with a foreach loop.yieldkeyword allows you to create something called iterator blocks. Iterator blocks have some neat properties (like lazy evaluation) and allow you easily create your own IEnumerable types without having to go to all the trouble of defining a new class first.Finally, it’s worth pointing out here that IDisposable is another interface worth further study, as it is used quite a bit in the framework and has direct language support similar to IEnumerable’s
foreachwith theusingkeyword.